Initial move of code from git repo.
|
|
@ -0,0 +1,674 @@
|
||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
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 may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program 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.
|
||||||
|
|
||||||
|
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
# file GENERATED by distutils, do NOT edit
|
||||||
|
COPYING
|
||||||
|
README
|
||||||
|
setup.py
|
||||||
|
archive/Joy-Programming.zip
|
||||||
|
archive/README
|
||||||
|
joy/__init__.py
|
||||||
|
joy/__main__.py
|
||||||
|
joy/joy.py
|
||||||
|
joy/library.py
|
||||||
|
joy/parser.py
|
||||||
|
joy/utils/__init__.py
|
||||||
|
joy/utils/pretty_print.py
|
||||||
|
joy/utils/stack.py
|
||||||
|
|
@ -0,0 +1,3 @@
|
||||||
|
include archive/*
|
||||||
|
include COPYING
|
||||||
|
recursive-include joy *.py
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
# My make-fu style is old and tired. I just want to have a few helper commands.
|
||||||
|
|
||||||
|
TESTDIR = ./test00
|
||||||
|
|
||||||
|
.PHONY: clean sdist test docs
|
||||||
|
|
||||||
|
|
||||||
|
clean:
|
||||||
|
$(RM) -r Joypy.egg-info/ dist/ $(TESTDIR)
|
||||||
|
find . -name '*.pyc' | xargs $(RM)
|
||||||
|
|
||||||
|
sdist:
|
||||||
|
python ./setup.py sdist
|
||||||
|
|
||||||
|
test: sdist
|
||||||
|
$(RM) -r $(TESTDIR)
|
||||||
|
virtualenv --system-site-packages --never-download $(TESTDIR)
|
||||||
|
. $(TESTDIR)/bin/activate && \
|
||||||
|
pip install --no-cache-dir --no-index ./dist/Joypy-0.1.tar.gz
|
||||||
|
echo "Type: source $(TESTDIR)/bin/activate"
|
||||||
|
|
||||||
|
|
||||||
|
docs:
|
||||||
|
cd ./docs && python -m nbconvert --to html *.ipynb
|
||||||
|
cd ./docs && python -m nbconvert --to markdown *.ipynb
|
||||||
|
|
@ -0,0 +1,237 @@
|
||||||
|
____ ____ _ _____ _____
|
||||||
|
| _ \| _ \ / \ | ___|_ _|
|
||||||
|
| | | | |_) | / A \ | |_ | |
|
||||||
|
| |_| | _ < / ___ \| _| | |
|
||||||
|
|____/|_| \_\_/ \_\_| |_|
|
||||||
|
|
||||||
|
--------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
Joypy
|
||||||
|
|
||||||
|
A dialect of Joy in Python.
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
Copyright © 2014, 2015, 2017 Simon Forman
|
||||||
|
|
||||||
|
This file is part of Joypy
|
||||||
|
|
||||||
|
Joypy 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.
|
||||||
|
|
||||||
|
Joypy 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
|
||||||
|
Joypy. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
§ Introduction
|
||||||
|
|
||||||
|
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 Joypy and the originals, other than being
|
||||||
|
written in Python, is that it works by the "Continuation-Passing Style".
|
||||||
|
In Joy, control-flow is done by combinators that expect quoted programs
|
||||||
|
on the stack and execute them in various ways. In Joypy they work by
|
||||||
|
changing the pending expression that the interpreter is about to execute.
|
||||||
|
In concrete terms, the combinators could work by making recursive calls
|
||||||
|
to the interpreter and all intermediate state would be held in the call
|
||||||
|
stack of the implementation language, in this Joypy implementation they
|
||||||
|
work instead by changing the pending expression and intermediate state
|
||||||
|
is put there.
|
||||||
|
|
||||||
|
As I study Joy I find that it is very aptly named. It is clear, concise,
|
||||||
|
and ameniable to advanced techniques for constructing bug-free software.
|
||||||
|
|
||||||
|
Developed by Manfred von Thun, don't know much about him, not much on
|
||||||
|
the web about Joy and von Thun (Von Thun?) See references below.
|
||||||
|
|
||||||
|
Because it has desirable properties (concise, highly factored) the
|
||||||
|
programming process changes, the ratio of designing to writing code
|
||||||
|
shifts in favor of design. The documentation becomes extensive while
|
||||||
|
the code shrinks to stable bodies of small well-factored incantations
|
||||||
|
that are highly expressive, much like mathematical papers consist of
|
||||||
|
large bodies of exposition interlaced with mathematical formula that
|
||||||
|
concisely and precisely express the meaning of the text.
|
||||||
|
|
||||||
|
The time and attention of the programmer shifts from thinking about the
|
||||||
|
language to thinking in the language, and the development process feels
|
||||||
|
more like deriving mathematical truths than like writing ad-hoc
|
||||||
|
solutions.
|
||||||
|
|
||||||
|
I hope that this package is useful in the sense that it provides an
|
||||||
|
additional joy interpreter (the binary in the archive from La Trobe seems
|
||||||
|
to run just fine on my modern Linux machine!) But I also hope that you
|
||||||
|
can read and understand the Python code and play with the implementation
|
||||||
|
itself.
|
||||||
|
|
||||||
|
The best source (no pun intended) for learning about Joy is the
|
||||||
|
information made available at the website of La Trobe University (see the
|
||||||
|
references section below for the URL) which contains source code for the
|
||||||
|
original C interpreter, Joy language source code for various functions,
|
||||||
|
and a great deal of fascinating material mostly written by Von Thun on
|
||||||
|
Joy and its deeper facets as well as how to program in it and several
|
||||||
|
interesting aspects. It's quite a treasure trove.
|
||||||
|
|
||||||
|
|
||||||
|
§ Installation
|
||||||
|
|
||||||
|
From PyPI in the usual way, e.g.:
|
||||||
|
|
||||||
|
pip install joypy
|
||||||
|
|
||||||
|
Or if you have downloaded the source, from the joypy directory:
|
||||||
|
|
||||||
|
python ./setup.py install
|
||||||
|
|
||||||
|
Or you can run the module from the joypy directory (see below.)
|
||||||
|
|
||||||
|
To start a crude REPL:
|
||||||
|
|
||||||
|
python -m joy
|
||||||
|
|
||||||
|
|
||||||
|
§ Basics of Joy
|
||||||
|
|
||||||
|
Joy is stack-based. There is a main stack that holds data items:
|
||||||
|
integers, floats, strings, functions, and sequences or quotes which hold
|
||||||
|
data items themselves.
|
||||||
|
|
||||||
|
23 1.8 'a string' "another" dup [21 18 /] [1 [2 [3]]]
|
||||||
|
|
||||||
|
A Joy expression is just a sequence of items, also called lists.
|
||||||
|
Sequences intended as programs are called "quoted programs". The
|
||||||
|
evaluation proceeds by iterating through the terms in the expression,
|
||||||
|
putting all literals onto the main stack and executing functions as they
|
||||||
|
are encountered. Functions receive the current stack and return the next
|
||||||
|
stack.
|
||||||
|
|
||||||
|
The main loop is very simple as most of the action happens through what
|
||||||
|
are called "combinators", which accept quoted programs on the stack and
|
||||||
|
run them in various ways. These combinators factor specific patterns
|
||||||
|
that provide the effect of control-flow in other languages (such as ifte
|
||||||
|
which is like if..then..else..) Combinators receive the current
|
||||||
|
expession in addition to the stack and return the next expression. As
|
||||||
|
mentioned above, the combinators in Joypy work by changing the pending
|
||||||
|
expression before returning it.
|
||||||
|
|
||||||
|
In general, where otherwise unspecified, the semantics of Joypy are that
|
||||||
|
of the underlying Python. That means, for example, that integers are
|
||||||
|
unbounded (whatever your machine can handle), strings cannot be added to
|
||||||
|
integers but can be multiplied, Boolean True and False are effectively
|
||||||
|
identical to ints 1 and 0, empty sequences are considered False, etc.
|
||||||
|
|
||||||
|
Nothing is done about Python exceptions currently, although it would be
|
||||||
|
possible to capture the stack and expression just before the exception
|
||||||
|
and build a robust and flexible error handler. Because they are both
|
||||||
|
just datastructures, you could immediately retry them under a debugger,
|
||||||
|
or edit either or both of the stack and expression. All state is in one
|
||||||
|
or the other.
|
||||||
|
|
||||||
|
§ Literals and Simple Functions
|
||||||
|
|
||||||
|
joy? 1 2 3
|
||||||
|
-> 3 2 1
|
||||||
|
|
||||||
|
joy? +
|
||||||
|
-> 5 1
|
||||||
|
|
||||||
|
joy? +
|
||||||
|
-> 6
|
||||||
|
|
||||||
|
joy? 7
|
||||||
|
-> 7 6
|
||||||
|
|
||||||
|
joy? *
|
||||||
|
-> 42
|
||||||
|
|
||||||
|
joy?
|
||||||
|
|
||||||
|
|
||||||
|
§ Simple Combinators
|
||||||
|
|
||||||
|
joy? 23 [0 >] [dup --] while
|
||||||
|
|
||||||
|
-> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
||||||
|
|
||||||
|
|
||||||
|
TODO:
|
||||||
|
|
||||||
|
§ Definitions and More Elaborate Functions
|
||||||
|
Refactoring
|
||||||
|
|
||||||
|
§ Programming and Metaprogramming
|
||||||
|
|
||||||
|
§ Further Reading
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
This Implementation
|
||||||
|
|
||||||
|
Run with:
|
||||||
|
|
||||||
|
python -m joy
|
||||||
|
|
||||||
|
joypy
|
||||||
|
|-- COPYING - license
|
||||||
|
|-- README - this file
|
||||||
|
|
|
||||||
|
|-- archive - info on Joy
|
||||||
|
| |-- Joy-Programming.zip
|
||||||
|
| `-- README
|
||||||
|
|
|
||||||
|
|-- docs - Various Examples and Demos
|
||||||
|
| |-- * - Jupyter Notebooks on Joypy and supporting modules
|
||||||
|
| `-- README - Table of Contents
|
||||||
|
|
|
||||||
|
|-- joy
|
||||||
|
| |-- joy.py - main loop, REPL
|
||||||
|
| |-- library.py - Functions, Combinators, Definitions
|
||||||
|
| |-- parser.py - convert text to Joy datastructures
|
||||||
|
| |
|
||||||
|
| `-- utils
|
||||||
|
| |-- pretty_print.py - convert Joy datastructures to text
|
||||||
|
| `-- stack.py - work with stacks
|
||||||
|
|
|
||||||
|
`-- setup.py
|
||||||
|
|
||||||
|
|
||||||
|
--------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
References
|
||||||
|
|
||||||
|
|
||||||
|
Wikipedia entry for Joy:
|
||||||
|
https://en.wikipedia.org/wiki/Joy_%28programming_language%29
|
||||||
|
|
||||||
|
|
||||||
|
Homepage at La Trobe University:
|
||||||
|
http://www.latrobe.edu.au/humanities/research/research-projects/past-projects/joy-programming-language
|
||||||
|
|
||||||
|
|
||||||
|
Misc...
|
||||||
|
|
||||||
|
Stack based - literals (as functions) - functions - combinators -
|
||||||
|
Refactoring and making new definitions - traces and comparing
|
||||||
|
performance - metaprogramming as programming, even the lowly integer
|
||||||
|
range function can be expressed in two phases: building a specialized
|
||||||
|
program and then executing it with a combinator - ?Partial evaluation?
|
||||||
|
- ?memoized dynamic dependency graphs? - algebra
|
||||||
|
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
This directory contains a copy of the material available from La Trobe
|
||||||
|
distributed in accordance with their respective licenses.
|
||||||
|
|
||||||
|
Joy-Programming.zip - Material on Joy from Manfred von Thun, et. al.
|
||||||
|
|
@ -0,0 +1,31 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright © 2014, 2015, 2017 Simon Forman
|
||||||
|
#
|
||||||
|
# This file is part of joy.py
|
||||||
|
#
|
||||||
|
# joy.py 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.
|
||||||
|
#
|
||||||
|
# joy.py 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 joy.py. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
#
|
||||||
|
from .library import initialize
|
||||||
|
from .joy import repl
|
||||||
|
|
||||||
|
print '''\
|
||||||
|
Joypy - Copyright © 2017 Simon Forman
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type "warranty".
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type "sharing" for details.
|
||||||
|
Type "words" to see a list of all words, and "[<name>] help" to print the
|
||||||
|
docs for a word.
|
||||||
|
'''
|
||||||
|
stack = repl(dictionary=initialize())
|
||||||
|
|
@ -0,0 +1,125 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
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 Joypy.
|
||||||
|
|
||||||
|
Joypy 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.
|
||||||
|
|
||||||
|
Joypy 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 Joypy. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
|
||||||
|
§ 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=())
|
||||||
|
|
||||||
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
|
try:
|
||||||
|
input = raw_input
|
||||||
|
except NameError:
|
||||||
|
pass
|
||||||
|
from traceback import print_exc, format_exc
|
||||||
|
from .parser import text_to_expression, ParseError, Symbol
|
||||||
|
from .utils.stack import stack_to_string
|
||||||
|
from .utils.pretty_print import TracePrinter
|
||||||
|
|
||||||
|
|
||||||
|
def joy(stack, expression, dictionary, viewer=None):
|
||||||
|
'''
|
||||||
|
Evaluate the Joy expression on the stack.
|
||||||
|
'''
|
||||||
|
while expression:
|
||||||
|
|
||||||
|
if viewer: viewer(stack, expression)
|
||||||
|
|
||||||
|
term, expression = expression
|
||||||
|
if isinstance(term, Symbol):
|
||||||
|
term = dictionary[term]
|
||||||
|
stack, expression, dictionary = term(stack, expression, dictionary)
|
||||||
|
else:
|
||||||
|
stack = term, stack
|
||||||
|
|
||||||
|
if viewer: viewer(stack, expression)
|
||||||
|
return stack, expression, dictionary
|
||||||
|
|
||||||
|
|
||||||
|
def run(text, stack, dictionary, viewer=None):
|
||||||
|
'''
|
||||||
|
Return the stack resulting from running the Joy code text on the stack.
|
||||||
|
'''
|
||||||
|
try:
|
||||||
|
expression = text_to_expression(text)
|
||||||
|
except ParseError as err:
|
||||||
|
print('Err:', err.message)
|
||||||
|
return stack, (), dictionary
|
||||||
|
return joy(stack, expression, dictionary, viewer)
|
||||||
|
|
||||||
|
|
||||||
|
def repl(stack=(), dictionary=None):
|
||||||
|
'''
|
||||||
|
Read-Evaluate-Print Loop
|
||||||
|
|
||||||
|
Accept input and run it on the stack, loop.
|
||||||
|
'''
|
||||||
|
if dictionary is None:
|
||||||
|
dictionary = {}
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
print()
|
||||||
|
print(stack_to_string(stack), '<-top')
|
||||||
|
print()
|
||||||
|
try:
|
||||||
|
text = input('joy? ')
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
break
|
||||||
|
viewer = TracePrinter()
|
||||||
|
try:
|
||||||
|
stack, _, dictionary = run(text, stack, dictionary, viewer.viewer)
|
||||||
|
except:
|
||||||
|
exc = format_exc() # Capture the exception.
|
||||||
|
viewer.print_() # Print the Joy trace.
|
||||||
|
print('-' * 73)
|
||||||
|
print(exc) # Print the original exception.
|
||||||
|
else:
|
||||||
|
viewer.print_()
|
||||||
|
except:
|
||||||
|
print_exc()
|
||||||
|
print()
|
||||||
|
return stack
|
||||||
|
|
@ -0,0 +1,110 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright © 2014, 2015, 2016, 2017 Simon Forman
|
||||||
|
#
|
||||||
|
# This file is part of Joypy.
|
||||||
|
#
|
||||||
|
# Joypy 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.
|
||||||
|
#
|
||||||
|
# Joypy 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 Joypy. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
#
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
§ Converting text to a joy expression.
|
||||||
|
|
||||||
|
This module exports a single function:
|
||||||
|
|
||||||
|
text_to_expression(text)
|
||||||
|
|
||||||
|
As well as a single Symbol class and a single Exception type:
|
||||||
|
|
||||||
|
ParseError
|
||||||
|
|
||||||
|
When supplied with a string this function returns a Python datastructure
|
||||||
|
that represents the Joy datastructure described by the text expression.
|
||||||
|
Any unbalanced square brackets will raise a ParseError.
|
||||||
|
'''
|
||||||
|
from re import Scanner
|
||||||
|
from .utils.stack import list_to_stack
|
||||||
|
|
||||||
|
|
||||||
|
class Symbol(str):
|
||||||
|
__repr__ = str.__str__
|
||||||
|
|
||||||
|
|
||||||
|
def text_to_expression(text):
|
||||||
|
'''
|
||||||
|
Convert a text to a Joy expression.
|
||||||
|
'''
|
||||||
|
return _parse(_tokenize(text))
|
||||||
|
|
||||||
|
|
||||||
|
class ParseError(ValueError): pass
|
||||||
|
|
||||||
|
|
||||||
|
def _tokenize(text):
|
||||||
|
'''
|
||||||
|
Convert a text into a stream of tokens, converting symbols using
|
||||||
|
symbol(token). Raise ValueError (with some of the failing text)
|
||||||
|
if the scan fails.
|
||||||
|
'''
|
||||||
|
tokens, rest = _scanner.scan(text)
|
||||||
|
if rest:
|
||||||
|
raise ParseError(
|
||||||
|
'Scan failed at position %i, %r'
|
||||||
|
% (len(text) - len(rest), rest[:10])
|
||||||
|
)
|
||||||
|
return tokens
|
||||||
|
|
||||||
|
|
||||||
|
def _parse(tokens):
|
||||||
|
'''
|
||||||
|
Return a stack/list expression of the tokens.
|
||||||
|
'''
|
||||||
|
frame = []
|
||||||
|
stack = []
|
||||||
|
for tok in tokens:
|
||||||
|
if tok == '[':
|
||||||
|
stack.append(frame)
|
||||||
|
frame = []
|
||||||
|
stack[-1].append(frame)
|
||||||
|
elif tok == ']':
|
||||||
|
try:
|
||||||
|
frame = stack.pop()
|
||||||
|
except IndexError:
|
||||||
|
raise ParseError('One or more extra closing brackets.')
|
||||||
|
frame[-1] = list_to_stack(frame[-1])
|
||||||
|
else:
|
||||||
|
frame.append(tok)
|
||||||
|
if stack:
|
||||||
|
raise ParseError('One or more unclosed brackets.')
|
||||||
|
return list_to_stack(frame)
|
||||||
|
|
||||||
|
|
||||||
|
def _scan_identifier(scanner, token): return Symbol(token)
|
||||||
|
def _scan_bracket(scanner, token): return token
|
||||||
|
def _scan_float(scanner, token): return float(token)
|
||||||
|
def _scan_int(scanner, token): return int(token)
|
||||||
|
def _scan_dstr(scanner, token): return token[1:-1].replace('\\"', '"')
|
||||||
|
def _scan_sstr(scanner, token): return token[1:-1].replace("\\'", "'")
|
||||||
|
|
||||||
|
|
||||||
|
_scanner = Scanner([
|
||||||
|
(r'-?\d+\.\d*', _scan_float),
|
||||||
|
(r'-?\d+', _scan_int),
|
||||||
|
(r'[•\w!@$%^&*()_+<>?|\/;:`~,.=-]+', _scan_identifier),
|
||||||
|
(r'\[|\]', _scan_bracket),
|
||||||
|
(r'"(?:[^"\\]|\\.)*"', _scan_dstr),
|
||||||
|
(r"'(?:[^'\\]|\\.)*'", _scan_sstr),
|
||||||
|
(r'\s+', None),
|
||||||
|
])
|
||||||
|
|
@ -0,0 +1,72 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright © 2016 Simon Forman
|
||||||
|
#
|
||||||
|
# This file is part of Joypy.
|
||||||
|
#
|
||||||
|
# Joypy 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.
|
||||||
|
#
|
||||||
|
# Joypy 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 Joypy. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
#
|
||||||
|
'''
|
||||||
|
Pretty printing support.
|
||||||
|
|
||||||
|
This is what does the formatting, e.g.:
|
||||||
|
|
||||||
|
. 23 18 mul 99 add
|
||||||
|
23 . 18 mul 99 add
|
||||||
|
23 18 . mul 99 add
|
||||||
|
414 . 99 add
|
||||||
|
414 99 . add
|
||||||
|
513 .
|
||||||
|
|
||||||
|
'''
|
||||||
|
# (Kinda clunky and hacky. This should be swapped out in favor of much
|
||||||
|
# smarter stuff.)
|
||||||
|
from __future__ import print_function
|
||||||
|
from traceback import print_exc
|
||||||
|
from .stack import expression_to_string, stack_to_string
|
||||||
|
|
||||||
|
|
||||||
|
class TracePrinter(object):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.history = []
|
||||||
|
|
||||||
|
def viewer(self, stack, expression):
|
||||||
|
'''Pass this method as the viewer to joy() function.'''
|
||||||
|
self.history.append((stack, expression))
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return '\n'.join(self.go())
|
||||||
|
|
||||||
|
def go(self):
|
||||||
|
max_stack_length = 0
|
||||||
|
lines = []
|
||||||
|
for stack, expression in self.history:
|
||||||
|
stack = stack_to_string(stack)
|
||||||
|
expression = expression_to_string(expression)
|
||||||
|
n = len(stack)
|
||||||
|
if n > max_stack_length:
|
||||||
|
max_stack_length = n
|
||||||
|
lines.append((n, '%s . %s' % (stack, expression)))
|
||||||
|
return [ # Prefix spaces to line up '.'s.
|
||||||
|
(' ' * (max_stack_length - length) + line)
|
||||||
|
for length, line in lines
|
||||||
|
]
|
||||||
|
|
||||||
|
def print_(self):
|
||||||
|
try:
|
||||||
|
print(self)
|
||||||
|
except:
|
||||||
|
print_exc()
|
||||||
|
print('Exception while printing viewer.')
|
||||||
|
|
@ -0,0 +1,154 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright © 2014, 2015, 2017 Simon Forman
|
||||||
|
#
|
||||||
|
# This file is part of joy.py
|
||||||
|
#
|
||||||
|
# joy.py 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.
|
||||||
|
#
|
||||||
|
# joy.py 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 joy.py. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
#
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
§ Stack
|
||||||
|
|
||||||
|
|
||||||
|
When talking about Joy we use the terms "stack", "list", "sequence" and
|
||||||
|
"aggregate" to mean the same thing: a simple datatype that 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
|
||||||
|
form of a stack with one or more items on it.
|
||||||
|
|
||||||
|
()
|
||||||
|
(1, ())
|
||||||
|
(2, (1, ()))
|
||||||
|
(3, (2, (1, ())))
|
||||||
|
...
|
||||||
|
|
||||||
|
And so on.
|
||||||
|
|
||||||
|
|
||||||
|
We have two very simple functions to build up a stack from a Python
|
||||||
|
iterable and also to iterate through a stack and yield its items
|
||||||
|
one-by-one in order, and two functions to generate string representations
|
||||||
|
of stacks:
|
||||||
|
|
||||||
|
list_to_stack()
|
||||||
|
|
||||||
|
iter_stack()
|
||||||
|
|
||||||
|
expression_to_string() (prints left-to-right)
|
||||||
|
|
||||||
|
stack_to_string() (prints right-to-left)
|
||||||
|
|
||||||
|
|
||||||
|
A word about the stack data structure.
|
||||||
|
|
||||||
|
Python has very nice "tuple packing and unpacking" in its syntax which
|
||||||
|
means we can directly "unpack" the expected arguments to a Joy function.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
def dup(stack):
|
||||||
|
head, tail = stack
|
||||||
|
return head, (head, tail)
|
||||||
|
|
||||||
|
We replace the argument "stack" by the expected structure of the stack,
|
||||||
|
in this case "(head, tail)", and Python takes care of de-structuring the
|
||||||
|
incoming argument and assigning values to the names. Note that Python
|
||||||
|
syntax doesn't require parentheses around tuples used in expressions
|
||||||
|
where they would be redundant.
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def list_to_stack(el, stack=()):
|
||||||
|
'''Convert a list (or other sequence) to a stack.
|
||||||
|
|
||||||
|
[1, 2, 3] -> (1, (2, (3, ())))
|
||||||
|
|
||||||
|
'''
|
||||||
|
for item in reversed(el):
|
||||||
|
stack = item, stack
|
||||||
|
return stack
|
||||||
|
|
||||||
|
|
||||||
|
def iter_stack(stack):
|
||||||
|
'''Iterate through the items on the stack.'''
|
||||||
|
while stack:
|
||||||
|
item, stack = stack
|
||||||
|
yield item
|
||||||
|
|
||||||
|
|
||||||
|
def stack_to_string(stack):
|
||||||
|
'''
|
||||||
|
Return a "pretty print" string for a stack.
|
||||||
|
|
||||||
|
The items are written right-to-left:
|
||||||
|
|
||||||
|
(top, (second, ...)) -> '... second top'
|
||||||
|
'''
|
||||||
|
f = lambda stack: reversed(list(iter_stack(stack)))
|
||||||
|
return _to_string(stack, f)
|
||||||
|
|
||||||
|
|
||||||
|
def expression_to_string(expression):
|
||||||
|
'''
|
||||||
|
Return a "pretty print" string for a expression.
|
||||||
|
|
||||||
|
The items are written left-to-right:
|
||||||
|
|
||||||
|
(top, (second, ...)) -> 'top second ...'
|
||||||
|
'''
|
||||||
|
return _to_string(expression, iter_stack)
|
||||||
|
|
||||||
|
|
||||||
|
def _to_string(stack, f):
|
||||||
|
if isinstance(stack, long): return str(stack).rstrip('L')
|
||||||
|
if not isinstance(stack, tuple): return repr(stack)
|
||||||
|
if not stack: return '' # shortcut
|
||||||
|
return ' '.join(map(_s, f(stack)))
|
||||||
|
|
||||||
|
|
||||||
|
_s = lambda s: (
|
||||||
|
'[%s]' % expression_to_string(s) if isinstance(s, tuple)
|
||||||
|
else str(s).rstrip('L') if isinstance(s, long)
|
||||||
|
else repr(s)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def pushback(quote, expression):
|
||||||
|
'''Concatinate quote onto expression.
|
||||||
|
|
||||||
|
In joy [1 2] [3 4] would become [1 2 3 4].
|
||||||
|
'''
|
||||||
|
return list_to_stack(list(iter_stack(quote)), expression)
|
||||||
|
|
||||||
|
|
||||||
|
def pick(s, n):
|
||||||
|
'''
|
||||||
|
Find the nth item on the stack. (Pick with zero is the same as "dup".)
|
||||||
|
'''
|
||||||
|
if n < 0:
|
||||||
|
raise ValueError
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
item, s = s
|
||||||
|
except ValueError:
|
||||||
|
raise IndexError
|
||||||
|
n -= 1
|
||||||
|
if n < 0:
|
||||||
|
break
|
||||||
|
return item
|
||||||
|
|
@ -0,0 +1,650 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Joypy\n",
|
||||||
|
"## Joy in Python\n",
|
||||||
|
"\n",
|
||||||
|
"This implementation is meant as a tool for exploring the programming model and method of Joy. Python seems like a great implementation language for Joy for several reasons.\n",
|
||||||
|
"\n",
|
||||||
|
"We can lean on the Python immutable types for our basic semantics and types: ints, floats, strings, and tuples, which enforces functional purity. We get garbage collection for free. Compilation via Cython. Glue language with loads of libraries."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### [Read-Eval-Print Loop (REPL)](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)\n",
|
||||||
|
"The main way to interact with the Joy interpreter is through a simple [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) that you start by running the package:\n",
|
||||||
|
"\n",
|
||||||
|
" $ python -m joy\n",
|
||||||
|
" Joypy - Copyright © 2017 Simon Forman\n",
|
||||||
|
" This program comes with ABSOLUTELY NO WARRANTY; for details type \"warranty\".\n",
|
||||||
|
" This is free software, and you are welcome to redistribute it\n",
|
||||||
|
" under certain conditions; type \"sharing\" for details.\n",
|
||||||
|
" Type \"words\" to see a list of all words, and \"[<name>] help\" to print the\n",
|
||||||
|
" docs for a word.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
" <-top\n",
|
||||||
|
"\n",
|
||||||
|
" joy? _\n",
|
||||||
|
"\n",
|
||||||
|
"The `<-top` marker points to the top of the (initially empty) stack. You can enter Joy notation at the prompt and a [trace of evaluation](#The-TracePrinter.) will be printed followed by the stack and prompt again:\n",
|
||||||
|
"\n",
|
||||||
|
" joy? 23 sqr 18 +\n",
|
||||||
|
" . 23 sqr 18 +\n",
|
||||||
|
" 23 . sqr 18 +\n",
|
||||||
|
" 23 . dup mul 18 +\n",
|
||||||
|
" 23 23 . mul 18 +\n",
|
||||||
|
" 529 . 18 +\n",
|
||||||
|
" 529 18 . +\n",
|
||||||
|
" 547 . \n",
|
||||||
|
"\n",
|
||||||
|
" 547 <-top\n",
|
||||||
|
"\n",
|
||||||
|
" joy? \n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Stacks (aka list, quote, sequence, etc.)\n",
|
||||||
|
"\n",
|
||||||
|
"In Joy, in addition to the types Boolean, integer, float, and string, there is a single sequence type represented by enclosing a sequence of terms in brackets `[...]`. This sequence type is used to represent both the stack and the expression. It is a [cons list](https://en.wikipedia.org/wiki/Cons#Lists) made from Python tuples."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"§ Stack\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"When talking about Joy we use the terms \"stack\", \"list\", \"sequence\" and\n",
|
||||||
|
"\"aggregate\" to mean the same thing: a simple datatype that permits\n",
|
||||||
|
"certain operations such as iterating and pushing and popping values from\n",
|
||||||
|
"(at least) one end.\n",
|
||||||
|
"\n",
|
||||||
|
"We use the venerable two-tuple recursive form of sequences where the\n",
|
||||||
|
"empty tuple () is the empty stack and (head, rest) gives the recursive\n",
|
||||||
|
"form of a stack with one or more items on it.\n",
|
||||||
|
"\n",
|
||||||
|
" ()\n",
|
||||||
|
" (1, ())\n",
|
||||||
|
" (2, (1, ()))\n",
|
||||||
|
" (3, (2, (1, ())))\n",
|
||||||
|
" ...\n",
|
||||||
|
"\n",
|
||||||
|
"And so on.\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"We have two very simple functions to build up a stack from a Python\n",
|
||||||
|
"iterable and also to iterate through a stack and yield its items\n",
|
||||||
|
"one-by-one in order, and two functions to generate string representations\n",
|
||||||
|
"of stacks:\n",
|
||||||
|
"\n",
|
||||||
|
" list_to_stack()\n",
|
||||||
|
"\n",
|
||||||
|
" iter_stack()\n",
|
||||||
|
"\n",
|
||||||
|
" expression_to_string() (prints left-to-right)\n",
|
||||||
|
"\n",
|
||||||
|
" stack_to_string() (prints right-to-left)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"A word about the stack data structure.\n",
|
||||||
|
"\n",
|
||||||
|
"Python has very nice \"tuple packing and unpacking\" in its syntax which\n",
|
||||||
|
"means we can directly \"unpack\" the expected arguments to a Joy function.\n",
|
||||||
|
"\n",
|
||||||
|
"For example:\n",
|
||||||
|
"\n",
|
||||||
|
" def dup(stack):\n",
|
||||||
|
" head, tail = stack\n",
|
||||||
|
" return head, (head, tail)\n",
|
||||||
|
"\n",
|
||||||
|
"We replace the argument \"stack\" by the expected structure of the stack,\n",
|
||||||
|
"in this case \"(head, tail)\", and Python takes care of de-structuring the\n",
|
||||||
|
"incoming argument and assigning values to the names. Note that Python\n",
|
||||||
|
"syntax doesn't require parentheses around tuples used in expressions\n",
|
||||||
|
"where they would be redundant.\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"import inspect\n",
|
||||||
|
"import joy.utils.stack\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"print inspect.getdoc(joy.utils.stack)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### The utility functions maintain order.\n",
|
||||||
|
"The 0th item in the list will be on the top of the stack and *vise versa*."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"(1, (2, (3, ())))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"joy.utils.stack.list_to_stack([1, 2, 3])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"[1, 2, 3]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"list(joy.utils.stack.iter_stack((1, (2, (3, ())))))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This requires reversing the sequence (or iterating backwards) otherwise:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"(3, (2, (1, ())))\n",
|
||||||
|
"[3, 2, 1]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"stack = ()\n",
|
||||||
|
"\n",
|
||||||
|
"for n in [1, 2, 3]:\n",
|
||||||
|
" stack = n, stack\n",
|
||||||
|
"\n",
|
||||||
|
"print stack\n",
|
||||||
|
"print list(joy.utils.stack.iter_stack(stack))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Purely Functional Datastructures.\n",
|
||||||
|
"Because Joy lists are made out of Python tuples they are immutable, so all Joy datastructures are *[purely functional](https://en.wikipedia.org/wiki/Purely_functional_data_structure)*."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# The `joy()` function.\n",
|
||||||
|
"## An Interpreter\n",
|
||||||
|
"The `joy()` function is extrememly simple. It accepts a stack, an expression, and a dictionary, and it iterates through the expression putting values onto the stack and delegating execution to functions it looks up in the dictionary.\n",
|
||||||
|
"\n",
|
||||||
|
"Each function is passed the stack, expression, and dictionary and returns them. Whatever the function returns becomes the new stack, expression, and dictionary. (The dictionary is passed to enable e.g. writing words that let you enter new words into the dictionary at runtime, which nothing does yet and may be a bad idea, and the `help` command.)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"def joy(stack, expression, dictionary, viewer=None):\n",
|
||||||
|
" '''\n",
|
||||||
|
" Evaluate the Joy expression on the stack.\n",
|
||||||
|
" '''\n",
|
||||||
|
" while expression:\n",
|
||||||
|
"\n",
|
||||||
|
" if viewer: viewer(stack, expression)\n",
|
||||||
|
"\n",
|
||||||
|
" term, expression = expression\n",
|
||||||
|
" if isinstance(term, Symbol):\n",
|
||||||
|
" term = dictionary[term]\n",
|
||||||
|
" stack, expression, dictionary = term(stack, expression, dictionary)\n",
|
||||||
|
" else:\n",
|
||||||
|
" stack = term, stack\n",
|
||||||
|
"\n",
|
||||||
|
" if viewer: viewer(stack, expression)\n",
|
||||||
|
" return stack, expression, dictionary\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"import joy.joy\n",
|
||||||
|
"\n",
|
||||||
|
"print inspect.getsource(joy.joy.joy)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### View function\n",
|
||||||
|
"The `joy()` function accepts a \"viewer\" function which it calls on each iteration passing the current stack and expression just before evaluation. This can be used for tracing, breakpoints, retrying after exceptions, or interrupting an evaluation and saving to disk or sending over the network to resume later. The stack and expression together contain all the state of the computation at each step."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### The `TracePrinter`.\n",
|
||||||
|
"\n",
|
||||||
|
"A `viewer` records each step of the evaluation of a Joy program. The `TracePrinter` has a facility for printing out a trace of the evaluation, one line per step. Each step is aligned to the current interpreter position, signified by a period separating the stack on the left from the pending expression (\"continuation\") on the right."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### [Continuation-Passing Style](https://en.wikipedia.org/wiki/Continuation-passing_style)\n",
|
||||||
|
"One day I thought, What happens if you rewrite Joy to use [CSP](https://en.wikipedia.org/wiki/Continuation-passing_style)? I made all the functions accept and return the expression as well as the stack and found that all the combinators could be rewritten to work by modifying the expression rather than making recursive calls to the `joy()` function."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Parser"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"§ Converting text to a joy expression.\n",
|
||||||
|
"\n",
|
||||||
|
"This module exports a single function:\n",
|
||||||
|
"\n",
|
||||||
|
" text_to_expression(text)\n",
|
||||||
|
"\n",
|
||||||
|
"As well as a single Symbol class and a single Exception type:\n",
|
||||||
|
"\n",
|
||||||
|
" ParseError\n",
|
||||||
|
"\n",
|
||||||
|
"When supplied with a string this function returns a Python datastructure\n",
|
||||||
|
"that represents the Joy datastructure described by the text expression.\n",
|
||||||
|
"Any unbalanced square brackets will raise a ParseError.\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"import joy.parser\n",
|
||||||
|
"\n",
|
||||||
|
"print inspect.getdoc(joy.parser)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The parser is extremely simple, the undocumented `re.Scanner` class does most of the tokenizing work and then you just build the tuple structure out of the tokens. There's no Abstract Syntax Tree or anything like that."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"def _parse(tokens):\n",
|
||||||
|
" '''\n",
|
||||||
|
" Return a stack/list expression of the tokens.\n",
|
||||||
|
" '''\n",
|
||||||
|
" frame = []\n",
|
||||||
|
" stack = []\n",
|
||||||
|
" for tok in tokens:\n",
|
||||||
|
" if tok == '[':\n",
|
||||||
|
" stack.append(frame)\n",
|
||||||
|
" frame = []\n",
|
||||||
|
" stack[-1].append(frame)\n",
|
||||||
|
" elif tok == ']':\n",
|
||||||
|
" try:\n",
|
||||||
|
" frame = stack.pop()\n",
|
||||||
|
" except IndexError:\n",
|
||||||
|
" raise ParseError('One or more extra closing brackets.')\n",
|
||||||
|
" frame[-1] = list_to_stack(frame[-1])\n",
|
||||||
|
" else:\n",
|
||||||
|
" frame.append(tok)\n",
|
||||||
|
" if stack:\n",
|
||||||
|
" raise ParseError('One or more unclosed brackets.')\n",
|
||||||
|
" return list_to_stack(frame)\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print inspect.getsource(joy.parser._parse)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"That's pretty much all there is to it."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"(1, (2, (3, (4, (5, ())))))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"joy.parser.text_to_expression('1 2 3 4 5') # A simple sequence."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"((1, (2, (3, ()))), (4, (5, ())))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"joy.parser.text_to_expression('[1 2 3] 4 5') # Three items, the first is a list with three items"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"(1, (23, (('four', ((-5.0, ()), (cons, ()))), (8888, ()))))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"joy.parser.text_to_expression('1 23 [\"four\" [-5.0] cons] 8888') # A mixed bag. cons is\n",
|
||||||
|
" # a Symbol, no lookup at\n",
|
||||||
|
" # parse-time. Haiku docs."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"((), ((), ((), ((), ((), ())))))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"joy.parser.text_to_expression('[][][][][]') # Five empty lists."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 12,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"((((((), ()), ()), ()), ()), ())"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 12,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"joy.parser.text_to_expression('[[[[[]]]]]') # Five nested lists."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Library\n",
|
||||||
|
"The Joy library of functions (aka commands, or \"words\" after Forth usage) encapsulates all the actual functionality (no pun intended) of the Joy system. There are simple functions such as addition `add` (or `+`, the library module supports aliases), and combinators which provide control-flow and higher-order operations."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 13,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"!= % & * *fraction *fraction0 + ++ - -- / < << <= <> = > >= >> ? ^ add anamorphism and app1 app2 app3 average b binary branch choice clear cleave concat cons dinfrirst dip dipd dipdd disenstacken div down_to_zero dudipd dup dupd dupdip enstacken eq first flatten floordiv gcd ge genrec getitem gt help i id ifte infra le least_fraction loop lshift lt map min mod modulus mul ne neg not nullary or over pam parse pm pop popd popdd popop pow pred primrec product quoted range range_to_zero rem remainder remove rest reverse roll< roll> rolldown rollup rshift run second select sharing shunt size sqr sqrt stack step sub succ sum swaack swap swoncat swons ternary third times truediv truthy tuck unary uncons unit unquoted unstack void warranty while words x xor zip •\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"import joy.library\n",
|
||||||
|
"\n",
|
||||||
|
"print ' '.join(sorted(joy.library.initialize()))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Many of the functions are defined in Python, like `dip`:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 14,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"def dip(stack, expression, dictionary):\n",
|
||||||
|
" (quote, (x, stack)) = stack\n",
|
||||||
|
" expression = x, expression\n",
|
||||||
|
" return stack, pushback(quote, expression), dictionary\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print inspect.getsource(joy.library.dip)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Some functions are defined in equations in terms of other functions. When the interpreter executes a definition function that function just pushes its body expression onto the pending expression (the continuation) and returns control to the interpreter."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 15,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"second == rest first\n",
|
||||||
|
"third == rest rest first\n",
|
||||||
|
"product == 1 swap [*] step\n",
|
||||||
|
"swons == swap cons\n",
|
||||||
|
"swoncat == swap concat\n",
|
||||||
|
"flatten == [] swap [concat] step\n",
|
||||||
|
"unit == [] cons\n",
|
||||||
|
"quoted == [unit] dip\n",
|
||||||
|
"unquoted == [i] dip\n",
|
||||||
|
"enstacken == stack [clear] dip\n",
|
||||||
|
"disenstacken == ? [uncons ?] loop pop\n",
|
||||||
|
"? == dup truthy\n",
|
||||||
|
"dinfrirst == dip infra first\n",
|
||||||
|
"nullary == [stack] dinfrirst\n",
|
||||||
|
"unary == [stack [pop] dip] dinfrirst\n",
|
||||||
|
"binary == [stack [popop] dip] dinfrirst\n",
|
||||||
|
"ternary == [stack [popop pop] dip] dinfrirst\n",
|
||||||
|
"pam == [i] map\n",
|
||||||
|
"run == [] swap infra\n",
|
||||||
|
"sqr == dup mul\n",
|
||||||
|
"size == 0 swap [pop ++] step\n",
|
||||||
|
"cleave == [i] app2 [popd] dip\n",
|
||||||
|
"average == [sum 1.0 *] [size] cleave /\n",
|
||||||
|
"gcd == 1 [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
"least_fraction == dup [gcd] infra [div] concat map\n",
|
||||||
|
"*fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons\n",
|
||||||
|
"*fraction0 == concat [[swap] dip * [*] dip] infra\n",
|
||||||
|
"down_to_zero == [0 >] [dup --] while\n",
|
||||||
|
"range_to_zero == unit [down_to_zero] infra\n",
|
||||||
|
"anamorphism == [pop []] swap [dip swons] genrec\n",
|
||||||
|
"range == [0 <=] [1 - dup] anamorphism\n",
|
||||||
|
"while == swap [nullary] cons dup dipd concat loop\n",
|
||||||
|
"dudipd == dup dipd\n",
|
||||||
|
"primrec == [i] genrec\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"print joy.library.definitions"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Currently, there's no function to add new definitions to the dictionary from \"within\" Joy code itself. Adding new definitions remains a meta-interpreter action. You have to do it yourself, in Python, and wash your hands afterward.\n",
|
||||||
|
"\n",
|
||||||
|
"It would be simple enough to define one, but it would open the door to *name binding* and break the idea that all state is captured in the stack and expression. There's an implicit *standard dictionary* that defines the actual semantics of the syntactic stack and expression datastructures (which only contain symbols, not the actual functions. Pickle some and see for yourself.)\n",
|
||||||
|
"\n",
|
||||||
|
"#### \"There should be only one.\"\n",
|
||||||
|
"\n",
|
||||||
|
"Which brings me to talking about one of my hopes and dreams for this notation: \"There should be only one.\" What I mean is that there should be one universal standard dictionary of commands, and all bespoke work done in a UI for purposes takes place by direct interaction and macros. There would be a *Grand Refactoring* biannually (two years, not six months, that's semi-annually) where any new definitions factored out of the usage and macros of the previous time, along with new algorithms and such, were entered into the dictionary and posted to e.g. IPFS.\n",
|
||||||
|
"\n",
|
||||||
|
"Code should not burgeon wildly, as it does today. The variety of code should map more-or-less to the well-factored variety of human computably-solvable problems. There shouldn't be dozens of chat apps, JS frameworks, programming languages. It's a waste of time, a [fractal \"thundering herd\" attack](https://en.wikipedia.org/wiki/Thundering_herd_problem) on human mentality.\n",
|
||||||
|
"\n",
|
||||||
|
"#### Literary Code Library\n",
|
||||||
|
"\n",
|
||||||
|
"If you read over the other notebooks you'll see that developing code in Joy is a lot like doing simple mathematics, and the descriptions of the code resemble math papers. The code also works the first time, no bugs. If you have any experience programming at all, you are probably skeptical, as I was, but it seems to work: deriving code mathematically seems to lead to fewer errors.\n",
|
||||||
|
"\n",
|
||||||
|
"But my point now is that this great ratio of textual explanation to wind up with code that consists of a few equations and could fit on an index card is highly desirable. Less code has fewer errors. The structure of Joy engenders a kind of thinking that seems to be very effective for developing structured processes.\n",
|
||||||
|
"\n",
|
||||||
|
"There seems to be an elegance and power to the notation.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
" "
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 2",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python2"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 2
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython2",
|
||||||
|
"version": "2.7.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,410 @@
|
||||||
|
|
||||||
|
# Joypy
|
||||||
|
## Joy in Python
|
||||||
|
|
||||||
|
This implementation is meant as a tool for exploring the programming model and method of Joy. Python seems like a great implementation language for Joy for several reasons.
|
||||||
|
|
||||||
|
We can lean on the Python immutable types for our basic semantics and types: ints, floats, strings, and tuples, which enforces functional purity. We get garbage collection for free. Compilation via Cython. Glue language with loads of libraries.
|
||||||
|
|
||||||
|
### [Read-Eval-Print Loop (REPL)](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)
|
||||||
|
The main way to interact with the Joy interpreter is through a simple [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop) that you start by running the package:
|
||||||
|
|
||||||
|
$ python -m joy
|
||||||
|
Joypy - Copyright © 2017 Simon Forman
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type "warranty".
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type "sharing" for details.
|
||||||
|
Type "words" to see a list of all words, and "[<name>] help" to print the
|
||||||
|
docs for a word.
|
||||||
|
|
||||||
|
|
||||||
|
<-top
|
||||||
|
|
||||||
|
joy? _
|
||||||
|
|
||||||
|
The `<-top` marker points to the top of the (initially empty) stack. You can enter Joy notation at the prompt and a [trace of evaluation](#The-TracePrinter.) will be printed followed by the stack and prompt again:
|
||||||
|
|
||||||
|
joy? 23 sqr 18 +
|
||||||
|
. 23 sqr 18 +
|
||||||
|
23 . sqr 18 +
|
||||||
|
23 . dup mul 18 +
|
||||||
|
23 23 . mul 18 +
|
||||||
|
529 . 18 +
|
||||||
|
529 18 . +
|
||||||
|
547 .
|
||||||
|
|
||||||
|
547 <-top
|
||||||
|
|
||||||
|
joy?
|
||||||
|
|
||||||
|
|
||||||
|
# Stacks (aka list, quote, sequence, etc.)
|
||||||
|
|
||||||
|
In Joy, in addition to the types Boolean, integer, float, and string, there is a single sequence type represented by enclosing a sequence of terms in brackets `[...]`. This sequence type is used to represent both the stack and the expression. It is a [cons list](https://en.wikipedia.org/wiki/Cons#Lists) made from Python tuples.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
import inspect
|
||||||
|
import joy.utils.stack
|
||||||
|
|
||||||
|
|
||||||
|
print inspect.getdoc(joy.utils.stack)
|
||||||
|
```
|
||||||
|
|
||||||
|
§ Stack
|
||||||
|
|
||||||
|
|
||||||
|
When talking about Joy we use the terms "stack", "list", "sequence" and
|
||||||
|
"aggregate" to mean the same thing: a simple datatype that 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
|
||||||
|
form of a stack with one or more items on it.
|
||||||
|
|
||||||
|
()
|
||||||
|
(1, ())
|
||||||
|
(2, (1, ()))
|
||||||
|
(3, (2, (1, ())))
|
||||||
|
...
|
||||||
|
|
||||||
|
And so on.
|
||||||
|
|
||||||
|
|
||||||
|
We have two very simple functions to build up a stack from a Python
|
||||||
|
iterable and also to iterate through a stack and yield its items
|
||||||
|
one-by-one in order, and two functions to generate string representations
|
||||||
|
of stacks:
|
||||||
|
|
||||||
|
list_to_stack()
|
||||||
|
|
||||||
|
iter_stack()
|
||||||
|
|
||||||
|
expression_to_string() (prints left-to-right)
|
||||||
|
|
||||||
|
stack_to_string() (prints right-to-left)
|
||||||
|
|
||||||
|
|
||||||
|
A word about the stack data structure.
|
||||||
|
|
||||||
|
Python has very nice "tuple packing and unpacking" in its syntax which
|
||||||
|
means we can directly "unpack" the expected arguments to a Joy function.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
def dup(stack):
|
||||||
|
head, tail = stack
|
||||||
|
return head, (head, tail)
|
||||||
|
|
||||||
|
We replace the argument "stack" by the expected structure of the stack,
|
||||||
|
in this case "(head, tail)", and Python takes care of de-structuring the
|
||||||
|
incoming argument and assigning values to the names. Note that Python
|
||||||
|
syntax doesn't require parentheses around tuples used in expressions
|
||||||
|
where they would be redundant.
|
||||||
|
|
||||||
|
|
||||||
|
### The utility functions maintain order.
|
||||||
|
The 0th item in the list will be on the top of the stack and *vise versa*.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
joy.utils.stack.list_to_stack([1, 2, 3])
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
(1, (2, (3, ())))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
list(joy.utils.stack.iter_stack((1, (2, (3, ())))))
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
[1, 2, 3]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
This requires reversing the sequence (or iterating backwards) otherwise:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
stack = ()
|
||||||
|
|
||||||
|
for n in [1, 2, 3]:
|
||||||
|
stack = n, stack
|
||||||
|
|
||||||
|
print stack
|
||||||
|
print list(joy.utils.stack.iter_stack(stack))
|
||||||
|
```
|
||||||
|
|
||||||
|
(3, (2, (1, ())))
|
||||||
|
[3, 2, 1]
|
||||||
|
|
||||||
|
|
||||||
|
### Purely Functional Datastructures.
|
||||||
|
Because Joy lists are made out of Python tuples they are immutable, so all Joy datastructures are *[purely functional](https://en.wikipedia.org/wiki/Purely_functional_data_structure)*.
|
||||||
|
|
||||||
|
# The `joy()` function.
|
||||||
|
## An Interpreter
|
||||||
|
The `joy()` function is extrememly simple. It accepts a stack, an expression, and a dictionary, and it iterates through the expression putting values onto the stack and delegating execution to functions it looks up in the dictionary.
|
||||||
|
|
||||||
|
Each function is passed the stack, expression, and dictionary and returns them. Whatever the function returns becomes the new stack, expression, and dictionary. (The dictionary is passed to enable e.g. writing words that let you enter new words into the dictionary at runtime, which nothing does yet and may be a bad idea, and the `help` command.)
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
import joy.joy
|
||||||
|
|
||||||
|
print inspect.getsource(joy.joy.joy)
|
||||||
|
```
|
||||||
|
|
||||||
|
def joy(stack, expression, dictionary, viewer=None):
|
||||||
|
'''
|
||||||
|
Evaluate the Joy expression on the stack.
|
||||||
|
'''
|
||||||
|
while expression:
|
||||||
|
|
||||||
|
if viewer: viewer(stack, expression)
|
||||||
|
|
||||||
|
term, expression = expression
|
||||||
|
if isinstance(term, Symbol):
|
||||||
|
term = dictionary[term]
|
||||||
|
stack, expression, dictionary = term(stack, expression, dictionary)
|
||||||
|
else:
|
||||||
|
stack = term, stack
|
||||||
|
|
||||||
|
if viewer: viewer(stack, expression)
|
||||||
|
return stack, expression, dictionary
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### View function
|
||||||
|
The `joy()` function accepts a "viewer" function which it calls on each iteration passing the current stack and expression just before evaluation. This can be used for tracing, breakpoints, retrying after exceptions, or interrupting an evaluation and saving to disk or sending over the network to resume later. The stack and expression together contain all the state of the computation at each step.
|
||||||
|
|
||||||
|
### The `TracePrinter`.
|
||||||
|
|
||||||
|
A `viewer` records each step of the evaluation of a Joy program. The `TracePrinter` has a facility for printing out a trace of the evaluation, one line per step. Each step is aligned to the current interpreter position, signified by a period separating the stack on the left from the pending expression ("continuation") on the right.
|
||||||
|
|
||||||
|
### [Continuation-Passing Style](https://en.wikipedia.org/wiki/Continuation-passing_style)
|
||||||
|
One day I thought, What happens if you rewrite Joy to use [CSP](https://en.wikipedia.org/wiki/Continuation-passing_style)? I made all the functions accept and return the expression as well as the stack and found that all the combinators could be rewritten to work by modifying the expression rather than making recursive calls to the `joy()` function.
|
||||||
|
|
||||||
|
# Parser
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
import joy.parser
|
||||||
|
|
||||||
|
print inspect.getdoc(joy.parser)
|
||||||
|
```
|
||||||
|
|
||||||
|
§ Converting text to a joy expression.
|
||||||
|
|
||||||
|
This module exports a single function:
|
||||||
|
|
||||||
|
text_to_expression(text)
|
||||||
|
|
||||||
|
As well as a single Symbol class and a single Exception type:
|
||||||
|
|
||||||
|
ParseError
|
||||||
|
|
||||||
|
When supplied with a string this function returns a Python datastructure
|
||||||
|
that represents the Joy datastructure described by the text expression.
|
||||||
|
Any unbalanced square brackets will raise a ParseError.
|
||||||
|
|
||||||
|
|
||||||
|
The parser is extremely simple, the undocumented `re.Scanner` class does most of the tokenizing work and then you just build the tuple structure out of the tokens. There's no Abstract Syntax Tree or anything like that.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
print inspect.getsource(joy.parser._parse)
|
||||||
|
```
|
||||||
|
|
||||||
|
def _parse(tokens):
|
||||||
|
'''
|
||||||
|
Return a stack/list expression of the tokens.
|
||||||
|
'''
|
||||||
|
frame = []
|
||||||
|
stack = []
|
||||||
|
for tok in tokens:
|
||||||
|
if tok == '[':
|
||||||
|
stack.append(frame)
|
||||||
|
frame = []
|
||||||
|
stack[-1].append(frame)
|
||||||
|
elif tok == ']':
|
||||||
|
try:
|
||||||
|
frame = stack.pop()
|
||||||
|
except IndexError:
|
||||||
|
raise ParseError('One or more extra closing brackets.')
|
||||||
|
frame[-1] = list_to_stack(frame[-1])
|
||||||
|
else:
|
||||||
|
frame.append(tok)
|
||||||
|
if stack:
|
||||||
|
raise ParseError('One or more unclosed brackets.')
|
||||||
|
return list_to_stack(frame)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
That's pretty much all there is to it.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
joy.parser.text_to_expression('1 2 3 4 5') # A simple sequence.
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
(1, (2, (3, (4, (5, ())))))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
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, ())))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
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, ()))))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
joy.parser.text_to_expression('[][][][][]') # Five empty lists.
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
((), ((), ((), ((), ((), ())))))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
joy.parser.text_to_expression('[[[[[]]]]]') # Five nested lists.
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
((((((), ()), ()), ()), ()), ())
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Library
|
||||||
|
The Joy library of functions (aka commands, or "words" after Forth usage) encapsulates all the actual functionality (no pun intended) of the Joy system. There are simple functions such as addition `add` (or `+`, the library module supports aliases), and combinators which provide control-flow and higher-order operations.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
import joy.library
|
||||||
|
|
||||||
|
print ' '.join(sorted(joy.library.initialize()))
|
||||||
|
```
|
||||||
|
|
||||||
|
!= % & * *fraction *fraction0 + ++ - -- / < << <= <> = > >= >> ? ^ add anamorphism and app1 app2 app3 average b binary branch choice clear cleave concat cons dinfrirst dip dipd dipdd disenstacken div down_to_zero dudipd dup dupd dupdip enstacken eq first flatten floordiv gcd ge genrec getitem gt help i id ifte infra le least_fraction loop lshift lt map min mod modulus mul ne neg not nullary or over pam parse pm pop popd popdd popop pow pred primrec product quoted range range_to_zero rem remainder remove rest reverse roll< roll> rolldown rollup rshift run second select sharing shunt size sqr sqrt stack step sub succ sum swaack swap swoncat swons ternary third times truediv truthy tuck unary uncons unit unquoted unstack void warranty while words x xor zip •
|
||||||
|
|
||||||
|
|
||||||
|
Many of the functions are defined in Python, like `dip`:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
print inspect.getsource(joy.library.dip)
|
||||||
|
```
|
||||||
|
|
||||||
|
def dip(stack, expression, dictionary):
|
||||||
|
(quote, (x, stack)) = stack
|
||||||
|
expression = x, expression
|
||||||
|
return stack, pushback(quote, expression), dictionary
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Some functions are defined in equations in terms of other functions. When the interpreter executes a definition function that function just pushes its body expression onto the pending expression (the continuation) and returns control to the interpreter.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
print joy.library.definitions
|
||||||
|
```
|
||||||
|
|
||||||
|
second == rest first
|
||||||
|
third == rest rest first
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Currently, there's no function to add new definitions to the dictionary from "within" Joy code itself. Adding new definitions remains a meta-interpreter action. You have to do it yourself, in Python, and wash your hands afterward.
|
||||||
|
|
||||||
|
It would be simple enough to define one, but it would open the door to *name binding* and break the idea that all state is captured in the stack and expression. There's an implicit *standard dictionary* that defines the actual semantics of the syntactic stack and expression datastructures (which only contain symbols, not the actual functions. Pickle some and see for yourself.)
|
||||||
|
|
||||||
|
#### "There should be only one."
|
||||||
|
|
||||||
|
Which brings me to talking about one of my hopes and dreams for this notation: "There should be only one." What I mean is that there should be one universal standard dictionary of commands, and all bespoke work done in a UI for purposes takes place by direct interaction and macros. There would be a *Grand Refactoring* biannually (two years, not six months, that's semi-annually) where any new definitions factored out of the usage and macros of the previous time, along with new algorithms and such, were entered into the dictionary and posted to e.g. IPFS.
|
||||||
|
|
||||||
|
Code should not burgeon wildly, as it does today. The variety of code should map more-or-less to the well-factored variety of human computably-solvable problems. There shouldn't be dozens of chat apps, JS frameworks, programming languages. It's a waste of time, a [fractal "thundering herd" attack](https://en.wikipedia.org/wiki/Thundering_herd_problem) on human mentality.
|
||||||
|
|
||||||
|
#### Literary Code Library
|
||||||
|
|
||||||
|
If you read over the other notebooks you'll see that developing code in Joy is a lot like doing simple mathematics, and the descriptions of the code resemble math papers. The code also works the first time, no bugs. If you have any experience programming at all, you are probably skeptical, as I was, but it seems to work: deriving code mathematically seems to lead to fewer errors.
|
||||||
|
|
||||||
|
But my point now is that this great ratio of textual explanation to wind up with code that consists of a few equations and could fit on an index card is highly desirable. Less code has fewer errors. The structure of Joy engenders a kind of thinking that seems to be very effective for developing structured processes.
|
||||||
|
|
||||||
|
There seems to be an elegance and power to the notation.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
|
||||||
|
```
|
||||||
|
|
@ -0,0 +1,240 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Preamble\n",
|
||||||
|
"\n",
|
||||||
|
"First, import what we need."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from joy.joy import run\n",
|
||||||
|
"from joy.library import initialize\n",
|
||||||
|
"from joy.utils.stack import stack_to_string\n",
|
||||||
|
"from joy.utils.pretty_print import TracePrinter"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Define a dictionary, an initial stack, and two helper functions to run Joy code and print results for us."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"D = initialize()\n",
|
||||||
|
"S = ()\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"def J(text):\n",
|
||||||
|
" print stack_to_string(run(text, S, D)[0])\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"def V(text):\n",
|
||||||
|
" tp = TracePrinter()\n",
|
||||||
|
" run(text, S, D, tp.viewer)\n",
|
||||||
|
" tp.print_()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Run some simple programs"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"41\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('23 18 +')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"15\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('45 30 gcd')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### With Viewer\n",
|
||||||
|
"\n",
|
||||||
|
"A `viewer` records each step of the evaluation of a Joy program. The `TracePrinter` has a facility for printing out a trace of the evaluation, one line per step. Each step is aligned to the current interpreter position, signified by a period separating the stack on the left from the pending expression (\"continuation\") on the right. I find these traces beautiful, like a kind of art."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . 23 18 +\n",
|
||||||
|
" 23 . 18 +\n",
|
||||||
|
"23 18 . +\n",
|
||||||
|
" 41 . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('23 18 +')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . 45 30 gcd\n",
|
||||||
|
" 45 . 30 gcd\n",
|
||||||
|
" 45 30 . gcd\n",
|
||||||
|
" 45 30 . 1 [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 45 30 1 . [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 45 30 1 [tuck modulus dup 0 >] . loop pop\n",
|
||||||
|
" 45 30 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 30 45 30 . modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 30 15 . dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 30 15 15 . 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 30 15 15 0 . > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 30 15 True . [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
"30 15 True [tuck modulus dup 0 >] . loop pop\n",
|
||||||
|
" 30 15 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 15 30 15 . modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 15 0 . dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 15 0 0 . 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 15 0 0 0 . > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 15 0 False . [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
"15 0 False [tuck modulus dup 0 >] . loop pop\n",
|
||||||
|
" 15 0 . pop\n",
|
||||||
|
" 15 . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('45 30 gcd')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Here's a longer trace."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . 96 27 gcd\n",
|
||||||
|
" 96 . 27 gcd\n",
|
||||||
|
" 96 27 . gcd\n",
|
||||||
|
" 96 27 . 1 [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 96 27 1 . [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 96 27 1 [tuck modulus dup 0 >] . loop pop\n",
|
||||||
|
" 96 27 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 27 96 27 . modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 27 15 . dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 27 15 15 . 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 27 15 15 0 . > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 27 15 True . [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
"27 15 True [tuck modulus dup 0 >] . loop pop\n",
|
||||||
|
" 27 15 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 15 27 15 . modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 15 12 . dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 15 12 12 . 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 15 12 12 0 . > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 15 12 True . [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
"15 12 True [tuck modulus dup 0 >] . loop pop\n",
|
||||||
|
" 15 12 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 12 15 12 . modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 12 3 . dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 12 3 3 . 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 12 3 3 0 . > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 12 3 True . [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 12 3 True [tuck modulus dup 0 >] . loop pop\n",
|
||||||
|
" 12 3 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 3 12 3 . modulus dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 3 0 . dup 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 3 0 0 . 0 > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 3 0 0 0 . > [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 3 0 False . [tuck modulus dup 0 >] loop pop\n",
|
||||||
|
" 3 0 False [tuck modulus dup 0 >] . loop pop\n",
|
||||||
|
" 3 0 . pop\n",
|
||||||
|
" 3 . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('96 27 gcd')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 2",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python2"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 2
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython2",
|
||||||
|
"version": "2.7.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,137 @@
|
||||||
|
|
||||||
|
### Preamble
|
||||||
|
|
||||||
|
First, import what we need.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from joy.joy import run
|
||||||
|
from joy.library import initialize
|
||||||
|
from joy.utils.stack import stack_to_string
|
||||||
|
from joy.utils.pretty_print import TracePrinter
|
||||||
|
```
|
||||||
|
|
||||||
|
Define a dictionary, an initial stack, and two helper functions to run Joy code and print results for us.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
D = initialize()
|
||||||
|
S = ()
|
||||||
|
|
||||||
|
|
||||||
|
def J(text):
|
||||||
|
print stack_to_string(run(text, S, D)[0])
|
||||||
|
|
||||||
|
|
||||||
|
def V(text):
|
||||||
|
tp = TracePrinter()
|
||||||
|
run(text, S, D, tp.viewer)
|
||||||
|
tp.print_()
|
||||||
|
```
|
||||||
|
|
||||||
|
### Run some simple programs
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('23 18 +')
|
||||||
|
```
|
||||||
|
|
||||||
|
41
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('45 30 gcd')
|
||||||
|
```
|
||||||
|
|
||||||
|
15
|
||||||
|
|
||||||
|
|
||||||
|
### With Viewer
|
||||||
|
|
||||||
|
A `viewer` records each step of the evaluation of a Joy program. The `TracePrinter` has a facility for printing out a trace of the evaluation, one line per step. Each step is aligned to the current interpreter position, signified by a period separating the stack on the left from the pending expression ("continuation") on the right. I find these traces beautiful, like a kind of art.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('23 18 +')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 23 18 +
|
||||||
|
23 . 18 +
|
||||||
|
23 18 . +
|
||||||
|
41 .
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('45 30 gcd')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 45 30 gcd
|
||||||
|
45 . 30 gcd
|
||||||
|
45 30 . gcd
|
||||||
|
45 30 . 1 [tuck modulus dup 0 >] loop pop
|
||||||
|
45 30 1 . [tuck modulus dup 0 >] loop pop
|
||||||
|
45 30 1 [tuck modulus dup 0 >] . loop pop
|
||||||
|
45 30 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
30 45 30 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
30 15 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
30 15 15 . 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
30 15 15 0 . > [tuck modulus dup 0 >] loop pop
|
||||||
|
30 15 True . [tuck modulus dup 0 >] loop pop
|
||||||
|
30 15 True [tuck modulus dup 0 >] . loop pop
|
||||||
|
30 15 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
15 30 15 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
15 0 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
15 0 0 . 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
15 0 0 0 . > [tuck modulus dup 0 >] loop pop
|
||||||
|
15 0 False . [tuck modulus dup 0 >] loop pop
|
||||||
|
15 0 False [tuck modulus dup 0 >] . loop pop
|
||||||
|
15 0 . pop
|
||||||
|
15 .
|
||||||
|
|
||||||
|
|
||||||
|
Here's a longer trace.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('96 27 gcd')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 96 27 gcd
|
||||||
|
96 . 27 gcd
|
||||||
|
96 27 . gcd
|
||||||
|
96 27 . 1 [tuck modulus dup 0 >] loop pop
|
||||||
|
96 27 1 . [tuck modulus dup 0 >] loop pop
|
||||||
|
96 27 1 [tuck modulus dup 0 >] . loop pop
|
||||||
|
96 27 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
27 96 27 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
27 15 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
27 15 15 . 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
27 15 15 0 . > [tuck modulus dup 0 >] loop pop
|
||||||
|
27 15 True . [tuck modulus dup 0 >] loop pop
|
||||||
|
27 15 True [tuck modulus dup 0 >] . loop pop
|
||||||
|
27 15 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
15 27 15 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
15 12 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
15 12 12 . 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
15 12 12 0 . > [tuck modulus dup 0 >] loop pop
|
||||||
|
15 12 True . [tuck modulus dup 0 >] loop pop
|
||||||
|
15 12 True [tuck modulus dup 0 >] . loop pop
|
||||||
|
15 12 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
12 15 12 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
12 3 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
12 3 3 . 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
12 3 3 0 . > [tuck modulus dup 0 >] loop pop
|
||||||
|
12 3 True . [tuck modulus dup 0 >] loop pop
|
||||||
|
12 3 True [tuck modulus dup 0 >] . loop pop
|
||||||
|
12 3 . tuck modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
3 12 3 . modulus dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
3 0 . dup 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
3 0 0 . 0 > [tuck modulus dup 0 >] loop pop
|
||||||
|
3 0 0 0 . > [tuck modulus dup 0 >] loop pop
|
||||||
|
3 0 False . [tuck modulus dup 0 >] loop pop
|
||||||
|
3 0 False [tuck modulus dup 0 >] . loop pop
|
||||||
|
3 0 . pop
|
||||||
|
3 .
|
||||||
|
|
||||||
|
|
@ -0,0 +1,694 @@
|
||||||
|
|
||||||
|
# [Project Euler, first problem: "Multiples of 3 and 5"](https://projecteuler.net/problem=1)
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from notebook_preamble import J, V, define
|
||||||
|
```
|
||||||
|
|
||||||
|
Let's create a predicate that returns `True` if a number is a multiple of 3 or 5 and `False` otherwise.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('P == [3 % not] dupdip 5 % not or')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('80 P')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 80 P
|
||||||
|
80 . P
|
||||||
|
80 . [3 % not] dupdip 5 % not or
|
||||||
|
80 [3 % not] . dupdip 5 % not or
|
||||||
|
80 . 3 % not 80 5 % not or
|
||||||
|
80 3 . % not 80 5 % not or
|
||||||
|
2 . not 80 5 % not or
|
||||||
|
False . 80 5 % not or
|
||||||
|
False 80 . 5 % not or
|
||||||
|
False 80 5 . % not or
|
||||||
|
False 0 . not or
|
||||||
|
False True . or
|
||||||
|
True .
|
||||||
|
|
||||||
|
|
||||||
|
Given the predicate function `P` a suitable program is:
|
||||||
|
|
||||||
|
PE1 == 1000 range [P] filter sum
|
||||||
|
|
||||||
|
This function generates a list of the integers from 0 to 999, filters
|
||||||
|
that list by `P`, and then sums the result.
|
||||||
|
|
||||||
|
Logically this is fine, but pragmatically we are doing more work than we
|
||||||
|
should be; we generate one thousand integers but actually use less than
|
||||||
|
half of them. A better solution would be to generate just the multiples
|
||||||
|
we want to sum, and to add them as we go rather than storing them and
|
||||||
|
adding summing them at the end.
|
||||||
|
|
||||||
|
At first I had the idea to use two counters and increase them by three
|
||||||
|
and five, respectively. This way we only generate the terms that we
|
||||||
|
actually want to sum. We have to proceed by incrementing the counter
|
||||||
|
that is lower, or if they are equal, the three counter, and we have to
|
||||||
|
take care not to double add numbers like 15 that are multiples of both
|
||||||
|
three and five.
|
||||||
|
|
||||||
|
This seemed a little clunky, so I tried a different approach.
|
||||||
|
|
||||||
|
Consider the first few terms in the series:
|
||||||
|
|
||||||
|
3 5 6 9 10 12 15 18 20 21 ...
|
||||||
|
|
||||||
|
Subtract each number from the one after it (subtracting 0 from 3):
|
||||||
|
|
||||||
|
3 5 6 9 10 12 15 18 20 21 24 25 27 30 ...
|
||||||
|
0 3 5 6 9 10 12 15 18 20 21 24 25 27 ...
|
||||||
|
-------------------------------------------
|
||||||
|
3 2 1 3 1 2 3 3 2 1 3 1 2 3 ...
|
||||||
|
|
||||||
|
You get this lovely repeating palindromic sequence:
|
||||||
|
|
||||||
|
3 2 1 3 1 2 3
|
||||||
|
|
||||||
|
To make a counter that increments by factors of 3 and 5 you just add
|
||||||
|
these differences to the counter one-by-one in a loop.
|
||||||
|
|
||||||
|
|
||||||
|
To make use of this sequence to increment a counter and sum terms as we
|
||||||
|
go we need a function that will accept the sum, the counter, and the next
|
||||||
|
term to add, and that adds the term to the counter and a copy of the
|
||||||
|
counter to the running sum. This function will do that:
|
||||||
|
|
||||||
|
PE1.1 == + [+] dupdip
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('PE1.1 == + [+] dupdip')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('0 0 3 PE1.1')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 0 0 3 PE1.1
|
||||||
|
0 . 0 3 PE1.1
|
||||||
|
0 0 . 3 PE1.1
|
||||||
|
0 0 3 . PE1.1
|
||||||
|
0 0 3 . + [+] dupdip
|
||||||
|
0 3 . [+] dupdip
|
||||||
|
0 3 [+] . dupdip
|
||||||
|
0 3 . + 3
|
||||||
|
3 . 3
|
||||||
|
3 3 .
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
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
|
||||||
|
0 . 0 [3 2 1 3 1 2 3] [PE1.1] step
|
||||||
|
0 0 . [3 2 1 3 1 2 3] [PE1.1] step
|
||||||
|
0 0 [3 2 1 3 1 2 3] . [PE1.1] step
|
||||||
|
0 0 [3 2 1 3 1 2 3] [PE1.1] . step
|
||||||
|
0 0 3 [PE1.1] . i [2 1 3 1 2 3] [PE1.1] step
|
||||||
|
0 0 3 . PE1.1 [2 1 3 1 2 3] [PE1.1] step
|
||||||
|
0 0 3 . + [+] dupdip [2 1 3 1 2 3] [PE1.1] step
|
||||||
|
0 3 . [+] dupdip [2 1 3 1 2 3] [PE1.1] step
|
||||||
|
0 3 [+] . dupdip [2 1 3 1 2 3] [PE1.1] step
|
||||||
|
0 3 . + 3 [2 1 3 1 2 3] [PE1.1] step
|
||||||
|
3 . 3 [2 1 3 1 2 3] [PE1.1] step
|
||||||
|
3 3 . [2 1 3 1 2 3] [PE1.1] step
|
||||||
|
3 3 [2 1 3 1 2 3] . [PE1.1] step
|
||||||
|
3 3 [2 1 3 1 2 3] [PE1.1] . step
|
||||||
|
3 3 2 [PE1.1] . i [1 3 1 2 3] [PE1.1] step
|
||||||
|
3 3 2 . PE1.1 [1 3 1 2 3] [PE1.1] step
|
||||||
|
3 3 2 . + [+] dupdip [1 3 1 2 3] [PE1.1] step
|
||||||
|
3 5 . [+] dupdip [1 3 1 2 3] [PE1.1] step
|
||||||
|
3 5 [+] . dupdip [1 3 1 2 3] [PE1.1] step
|
||||||
|
3 5 . + 5 [1 3 1 2 3] [PE1.1] step
|
||||||
|
8 . 5 [1 3 1 2 3] [PE1.1] step
|
||||||
|
8 5 . [1 3 1 2 3] [PE1.1] step
|
||||||
|
8 5 [1 3 1 2 3] . [PE1.1] step
|
||||||
|
8 5 [1 3 1 2 3] [PE1.1] . step
|
||||||
|
8 5 1 [PE1.1] . i [3 1 2 3] [PE1.1] step
|
||||||
|
8 5 1 . PE1.1 [3 1 2 3] [PE1.1] step
|
||||||
|
8 5 1 . + [+] dupdip [3 1 2 3] [PE1.1] step
|
||||||
|
8 6 . [+] dupdip [3 1 2 3] [PE1.1] step
|
||||||
|
8 6 [+] . dupdip [3 1 2 3] [PE1.1] step
|
||||||
|
8 6 . + 6 [3 1 2 3] [PE1.1] step
|
||||||
|
14 . 6 [3 1 2 3] [PE1.1] step
|
||||||
|
14 6 . [3 1 2 3] [PE1.1] step
|
||||||
|
14 6 [3 1 2 3] . [PE1.1] step
|
||||||
|
14 6 [3 1 2 3] [PE1.1] . step
|
||||||
|
14 6 3 [PE1.1] . i [1 2 3] [PE1.1] step
|
||||||
|
14 6 3 . PE1.1 [1 2 3] [PE1.1] step
|
||||||
|
14 6 3 . + [+] dupdip [1 2 3] [PE1.1] step
|
||||||
|
14 9 . [+] dupdip [1 2 3] [PE1.1] step
|
||||||
|
14 9 [+] . dupdip [1 2 3] [PE1.1] step
|
||||||
|
14 9 . + 9 [1 2 3] [PE1.1] step
|
||||||
|
23 . 9 [1 2 3] [PE1.1] step
|
||||||
|
23 9 . [1 2 3] [PE1.1] step
|
||||||
|
23 9 [1 2 3] . [PE1.1] step
|
||||||
|
23 9 [1 2 3] [PE1.1] . step
|
||||||
|
23 9 1 [PE1.1] . i [2 3] [PE1.1] step
|
||||||
|
23 9 1 . PE1.1 [2 3] [PE1.1] step
|
||||||
|
23 9 1 . + [+] dupdip [2 3] [PE1.1] step
|
||||||
|
23 10 . [+] dupdip [2 3] [PE1.1] step
|
||||||
|
23 10 [+] . dupdip [2 3] [PE1.1] step
|
||||||
|
23 10 . + 10 [2 3] [PE1.1] step
|
||||||
|
33 . 10 [2 3] [PE1.1] step
|
||||||
|
33 10 . [2 3] [PE1.1] step
|
||||||
|
33 10 [2 3] . [PE1.1] step
|
||||||
|
33 10 [2 3] [PE1.1] . step
|
||||||
|
33 10 2 [PE1.1] . i [3] [PE1.1] step
|
||||||
|
33 10 2 . PE1.1 [3] [PE1.1] step
|
||||||
|
33 10 2 . + [+] dupdip [3] [PE1.1] step
|
||||||
|
33 12 . [+] dupdip [3] [PE1.1] step
|
||||||
|
33 12 [+] . dupdip [3] [PE1.1] step
|
||||||
|
33 12 . + 12 [3] [PE1.1] step
|
||||||
|
45 . 12 [3] [PE1.1] step
|
||||||
|
45 12 . [3] [PE1.1] step
|
||||||
|
45 12 [3] . [PE1.1] step
|
||||||
|
45 12 [3] [PE1.1] . step
|
||||||
|
45 12 3 [PE1.1] . i
|
||||||
|
45 12 3 . PE1.1
|
||||||
|
45 12 3 . + [+] dupdip
|
||||||
|
45 15 . [+] dupdip
|
||||||
|
45 15 [+] . dupdip
|
||||||
|
45 15 . + 15
|
||||||
|
60 . 15
|
||||||
|
60 15 .
|
||||||
|
|
||||||
|
|
||||||
|
So one `step` through all seven terms brings the counter to 15 and the total to 60.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
1000 / 15
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
66
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
66 * 15
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
990
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
1000 - 990
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
10
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
We only want the terms *less than* 1000.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
999 - 990
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
9
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
```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')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('PE1')
|
||||||
|
```
|
||||||
|
|
||||||
|
233168
|
||||||
|
|
||||||
|
|
||||||
|
This form uses no extra storage and produces no unused summands. It's
|
||||||
|
good but there's one more trick we can apply. The list of seven terms
|
||||||
|
takes up at least seven bytes. But notice that all of the terms are less
|
||||||
|
than four, and so each can fit in just two bits. We could store all
|
||||||
|
seven terms in just fourteen bits and use masking and shifts to pick out
|
||||||
|
each term as we go. This will use less space and save time loading whole
|
||||||
|
integer terms from the list.
|
||||||
|
|
||||||
|
3 2 1 3 1 2 3
|
||||||
|
0b 11 10 01 11 01 10 11 == 14811
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
0b11100111011011
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
14811
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('PE1.2 == [3 & PE1.1] dupdip 2 >>')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('0 0 14811 PE1.2')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 0 0 14811 PE1.2
|
||||||
|
0 . 0 14811 PE1.2
|
||||||
|
0 0 . 14811 PE1.2
|
||||||
|
0 0 14811 . PE1.2
|
||||||
|
0 0 14811 . [3 & PE1.1] dupdip 2 >>
|
||||||
|
0 0 14811 [3 & PE1.1] . dupdip 2 >>
|
||||||
|
0 0 14811 . 3 & PE1.1 14811 2 >>
|
||||||
|
0 0 14811 3 . & PE1.1 14811 2 >>
|
||||||
|
0 0 3 . PE1.1 14811 2 >>
|
||||||
|
0 0 3 . + [+] dupdip 14811 2 >>
|
||||||
|
0 3 . [+] dupdip 14811 2 >>
|
||||||
|
0 3 [+] . dupdip 14811 2 >>
|
||||||
|
0 3 . + 3 14811 2 >>
|
||||||
|
3 . 3 14811 2 >>
|
||||||
|
3 3 . 14811 2 >>
|
||||||
|
3 3 14811 . 2 >>
|
||||||
|
3 3 14811 2 . >>
|
||||||
|
3 3 3702 .
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('3 3 3702 PE1.2')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 3 3 3702 PE1.2
|
||||||
|
3 . 3 3702 PE1.2
|
||||||
|
3 3 . 3702 PE1.2
|
||||||
|
3 3 3702 . PE1.2
|
||||||
|
3 3 3702 . [3 & PE1.1] dupdip 2 >>
|
||||||
|
3 3 3702 [3 & PE1.1] . dupdip 2 >>
|
||||||
|
3 3 3702 . 3 & PE1.1 3702 2 >>
|
||||||
|
3 3 3702 3 . & PE1.1 3702 2 >>
|
||||||
|
3 3 2 . PE1.1 3702 2 >>
|
||||||
|
3 3 2 . + [+] dupdip 3702 2 >>
|
||||||
|
3 5 . [+] dupdip 3702 2 >>
|
||||||
|
3 5 [+] . dupdip 3702 2 >>
|
||||||
|
3 5 . + 5 3702 2 >>
|
||||||
|
8 . 5 3702 2 >>
|
||||||
|
8 5 . 3702 2 >>
|
||||||
|
8 5 3702 . 2 >>
|
||||||
|
8 5 3702 2 . >>
|
||||||
|
8 5 925 .
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('0 0 14811 7 [PE1.2] times pop')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 0 0 14811 7 [PE1.2] times pop
|
||||||
|
0 . 0 14811 7 [PE1.2] times pop
|
||||||
|
0 0 . 14811 7 [PE1.2] times pop
|
||||||
|
0 0 14811 . 7 [PE1.2] times pop
|
||||||
|
0 0 14811 7 . [PE1.2] times pop
|
||||||
|
0 0 14811 7 [PE1.2] . times pop
|
||||||
|
0 0 14811 [PE1.2] . i 6 [PE1.2] times pop
|
||||||
|
0 0 14811 . PE1.2 6 [PE1.2] times pop
|
||||||
|
0 0 14811 . [3 & PE1.1] dupdip 2 >> 6 [PE1.2] times pop
|
||||||
|
0 0 14811 [3 & PE1.1] . dupdip 2 >> 6 [PE1.2] times pop
|
||||||
|
0 0 14811 . 3 & PE1.1 14811 2 >> 6 [PE1.2] times pop
|
||||||
|
0 0 14811 3 . & PE1.1 14811 2 >> 6 [PE1.2] times pop
|
||||||
|
0 0 3 . PE1.1 14811 2 >> 6 [PE1.2] times pop
|
||||||
|
0 0 3 . + [+] dupdip 14811 2 >> 6 [PE1.2] times pop
|
||||||
|
0 3 . [+] dupdip 14811 2 >> 6 [PE1.2] times pop
|
||||||
|
0 3 [+] . dupdip 14811 2 >> 6 [PE1.2] times pop
|
||||||
|
0 3 . + 3 14811 2 >> 6 [PE1.2] times pop
|
||||||
|
3 . 3 14811 2 >> 6 [PE1.2] times pop
|
||||||
|
3 3 . 14811 2 >> 6 [PE1.2] times pop
|
||||||
|
3 3 14811 . 2 >> 6 [PE1.2] times pop
|
||||||
|
3 3 14811 2 . >> 6 [PE1.2] times pop
|
||||||
|
3 3 3702 . 6 [PE1.2] times pop
|
||||||
|
3 3 3702 6 . [PE1.2] times pop
|
||||||
|
3 3 3702 6 [PE1.2] . times pop
|
||||||
|
3 3 3702 [PE1.2] . i 5 [PE1.2] times pop
|
||||||
|
3 3 3702 . PE1.2 5 [PE1.2] times pop
|
||||||
|
3 3 3702 . [3 & PE1.1] dupdip 2 >> 5 [PE1.2] times pop
|
||||||
|
3 3 3702 [3 & PE1.1] . dupdip 2 >> 5 [PE1.2] times pop
|
||||||
|
3 3 3702 . 3 & PE1.1 3702 2 >> 5 [PE1.2] times pop
|
||||||
|
3 3 3702 3 . & PE1.1 3702 2 >> 5 [PE1.2] times pop
|
||||||
|
3 3 2 . PE1.1 3702 2 >> 5 [PE1.2] times pop
|
||||||
|
3 3 2 . + [+] dupdip 3702 2 >> 5 [PE1.2] times pop
|
||||||
|
3 5 . [+] dupdip 3702 2 >> 5 [PE1.2] times pop
|
||||||
|
3 5 [+] . dupdip 3702 2 >> 5 [PE1.2] times pop
|
||||||
|
3 5 . + 5 3702 2 >> 5 [PE1.2] times pop
|
||||||
|
8 . 5 3702 2 >> 5 [PE1.2] times pop
|
||||||
|
8 5 . 3702 2 >> 5 [PE1.2] times pop
|
||||||
|
8 5 3702 . 2 >> 5 [PE1.2] times pop
|
||||||
|
8 5 3702 2 . >> 5 [PE1.2] times pop
|
||||||
|
8 5 925 . 5 [PE1.2] times pop
|
||||||
|
8 5 925 5 . [PE1.2] times pop
|
||||||
|
8 5 925 5 [PE1.2] . times pop
|
||||||
|
8 5 925 [PE1.2] . i 4 [PE1.2] times pop
|
||||||
|
8 5 925 . PE1.2 4 [PE1.2] times pop
|
||||||
|
8 5 925 . [3 & PE1.1] dupdip 2 >> 4 [PE1.2] times pop
|
||||||
|
8 5 925 [3 & PE1.1] . dupdip 2 >> 4 [PE1.2] times pop
|
||||||
|
8 5 925 . 3 & PE1.1 925 2 >> 4 [PE1.2] times pop
|
||||||
|
8 5 925 3 . & PE1.1 925 2 >> 4 [PE1.2] times pop
|
||||||
|
8 5 1 . PE1.1 925 2 >> 4 [PE1.2] times pop
|
||||||
|
8 5 1 . + [+] dupdip 925 2 >> 4 [PE1.2] times pop
|
||||||
|
8 6 . [+] dupdip 925 2 >> 4 [PE1.2] times pop
|
||||||
|
8 6 [+] . dupdip 925 2 >> 4 [PE1.2] times pop
|
||||||
|
8 6 . + 6 925 2 >> 4 [PE1.2] times pop
|
||||||
|
14 . 6 925 2 >> 4 [PE1.2] times pop
|
||||||
|
14 6 . 925 2 >> 4 [PE1.2] times pop
|
||||||
|
14 6 925 . 2 >> 4 [PE1.2] times pop
|
||||||
|
14 6 925 2 . >> 4 [PE1.2] times pop
|
||||||
|
14 6 231 . 4 [PE1.2] times pop
|
||||||
|
14 6 231 4 . [PE1.2] times pop
|
||||||
|
14 6 231 4 [PE1.2] . times pop
|
||||||
|
14 6 231 [PE1.2] . i 3 [PE1.2] times pop
|
||||||
|
14 6 231 . PE1.2 3 [PE1.2] times pop
|
||||||
|
14 6 231 . [3 & PE1.1] dupdip 2 >> 3 [PE1.2] times pop
|
||||||
|
14 6 231 [3 & PE1.1] . dupdip 2 >> 3 [PE1.2] times pop
|
||||||
|
14 6 231 . 3 & PE1.1 231 2 >> 3 [PE1.2] times pop
|
||||||
|
14 6 231 3 . & PE1.1 231 2 >> 3 [PE1.2] times pop
|
||||||
|
14 6 3 . PE1.1 231 2 >> 3 [PE1.2] times pop
|
||||||
|
14 6 3 . + [+] dupdip 231 2 >> 3 [PE1.2] times pop
|
||||||
|
14 9 . [+] dupdip 231 2 >> 3 [PE1.2] times pop
|
||||||
|
14 9 [+] . dupdip 231 2 >> 3 [PE1.2] times pop
|
||||||
|
14 9 . + 9 231 2 >> 3 [PE1.2] times pop
|
||||||
|
23 . 9 231 2 >> 3 [PE1.2] times pop
|
||||||
|
23 9 . 231 2 >> 3 [PE1.2] times pop
|
||||||
|
23 9 231 . 2 >> 3 [PE1.2] times pop
|
||||||
|
23 9 231 2 . >> 3 [PE1.2] times pop
|
||||||
|
23 9 57 . 3 [PE1.2] times pop
|
||||||
|
23 9 57 3 . [PE1.2] times pop
|
||||||
|
23 9 57 3 [PE1.2] . times pop
|
||||||
|
23 9 57 [PE1.2] . i 2 [PE1.2] times pop
|
||||||
|
23 9 57 . PE1.2 2 [PE1.2] times pop
|
||||||
|
23 9 57 . [3 & PE1.1] dupdip 2 >> 2 [PE1.2] times pop
|
||||||
|
23 9 57 [3 & PE1.1] . dupdip 2 >> 2 [PE1.2] times pop
|
||||||
|
23 9 57 . 3 & PE1.1 57 2 >> 2 [PE1.2] times pop
|
||||||
|
23 9 57 3 . & PE1.1 57 2 >> 2 [PE1.2] times pop
|
||||||
|
23 9 1 . PE1.1 57 2 >> 2 [PE1.2] times pop
|
||||||
|
23 9 1 . + [+] dupdip 57 2 >> 2 [PE1.2] times pop
|
||||||
|
23 10 . [+] dupdip 57 2 >> 2 [PE1.2] times pop
|
||||||
|
23 10 [+] . dupdip 57 2 >> 2 [PE1.2] times pop
|
||||||
|
23 10 . + 10 57 2 >> 2 [PE1.2] times pop
|
||||||
|
33 . 10 57 2 >> 2 [PE1.2] times pop
|
||||||
|
33 10 . 57 2 >> 2 [PE1.2] times pop
|
||||||
|
33 10 57 . 2 >> 2 [PE1.2] times pop
|
||||||
|
33 10 57 2 . >> 2 [PE1.2] times pop
|
||||||
|
33 10 14 . 2 [PE1.2] times pop
|
||||||
|
33 10 14 2 . [PE1.2] times pop
|
||||||
|
33 10 14 2 [PE1.2] . times pop
|
||||||
|
33 10 14 [PE1.2] . i 1 [PE1.2] times pop
|
||||||
|
33 10 14 . PE1.2 1 [PE1.2] times pop
|
||||||
|
33 10 14 . [3 & PE1.1] dupdip 2 >> 1 [PE1.2] times pop
|
||||||
|
33 10 14 [3 & PE1.1] . dupdip 2 >> 1 [PE1.2] times pop
|
||||||
|
33 10 14 . 3 & PE1.1 14 2 >> 1 [PE1.2] times pop
|
||||||
|
33 10 14 3 . & PE1.1 14 2 >> 1 [PE1.2] times pop
|
||||||
|
33 10 2 . PE1.1 14 2 >> 1 [PE1.2] times pop
|
||||||
|
33 10 2 . + [+] dupdip 14 2 >> 1 [PE1.2] times pop
|
||||||
|
33 12 . [+] dupdip 14 2 >> 1 [PE1.2] times pop
|
||||||
|
33 12 [+] . dupdip 14 2 >> 1 [PE1.2] times pop
|
||||||
|
33 12 . + 12 14 2 >> 1 [PE1.2] times pop
|
||||||
|
45 . 12 14 2 >> 1 [PE1.2] times pop
|
||||||
|
45 12 . 14 2 >> 1 [PE1.2] times pop
|
||||||
|
45 12 14 . 2 >> 1 [PE1.2] times pop
|
||||||
|
45 12 14 2 . >> 1 [PE1.2] times pop
|
||||||
|
45 12 3 . 1 [PE1.2] times pop
|
||||||
|
45 12 3 1 . [PE1.2] times pop
|
||||||
|
45 12 3 1 [PE1.2] . times pop
|
||||||
|
45 12 3 [PE1.2] . i pop
|
||||||
|
45 12 3 . PE1.2 pop
|
||||||
|
45 12 3 . [3 & PE1.1] dupdip 2 >> pop
|
||||||
|
45 12 3 [3 & PE1.1] . dupdip 2 >> pop
|
||||||
|
45 12 3 . 3 & PE1.1 3 2 >> pop
|
||||||
|
45 12 3 3 . & PE1.1 3 2 >> pop
|
||||||
|
45 12 3 . PE1.1 3 2 >> pop
|
||||||
|
45 12 3 . + [+] dupdip 3 2 >> pop
|
||||||
|
45 15 . [+] dupdip 3 2 >> pop
|
||||||
|
45 15 [+] . dupdip 3 2 >> pop
|
||||||
|
45 15 . + 15 3 2 >> pop
|
||||||
|
60 . 15 3 2 >> pop
|
||||||
|
60 15 . 3 2 >> pop
|
||||||
|
60 15 3 . 2 >> pop
|
||||||
|
60 15 3 2 . >> pop
|
||||||
|
60 15 0 . pop
|
||||||
|
60 15 .
|
||||||
|
|
||||||
|
|
||||||
|
And so we have at last:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('PE1 == 0 0 66 [14811 7 [PE1.2] times pop] times 14811 4 [PE1.2] times popop')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('PE1')
|
||||||
|
```
|
||||||
|
|
||||||
|
233168
|
||||||
|
|
||||||
|
|
||||||
|
Let's refactor.
|
||||||
|
|
||||||
|
14811 7 [PE1.2] times pop
|
||||||
|
14811 4 [PE1.2] times pop
|
||||||
|
14811 n [PE1.2] times pop
|
||||||
|
n 14811 swap [PE1.2] times pop
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('PE1.3 == 14811 swap [PE1.2] times pop')
|
||||||
|
```
|
||||||
|
|
||||||
|
Now we can simplify the definition above:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('PE1')
|
||||||
|
```
|
||||||
|
|
||||||
|
233168
|
||||||
|
|
||||||
|
|
||||||
|
Here's our joy program all in one place. It doesn't make so much sense, but if you have read through the above description of how it was derived I hope it's clear.
|
||||||
|
|
||||||
|
PE1.1 == + [+] dupdip
|
||||||
|
PE1.2 == [3 & PE1.1] dupdip 2 >>
|
||||||
|
PE1.3 == 14811 swap [PE1.2] times pop
|
||||||
|
PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop
|
||||||
|
|
||||||
|
# Generator Version
|
||||||
|
It's a little clunky iterating sixty-six times though the seven numbers 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.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('PE1.terms == [0 swap [dup [pop 14811] [] branch [3 &] dupdip 2 >>] dip rest cons]')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
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]
|
||||||
|
|
||||||
|
|
||||||
|
We know from above that we need sixty-six times seven then four more terms to reach up to but not over one thousand.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('7 66 * 4 +')
|
||||||
|
```
|
||||||
|
|
||||||
|
466
|
||||||
|
|
||||||
|
|
||||||
|
### Here they are...
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
### ...and they do sum to 999.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[PE1.terms 466 [x] times pop] run sum')
|
||||||
|
```
|
||||||
|
|
||||||
|
999
|
||||||
|
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('0 0 PE1.terms 466 [x [PE1.1] dip] times popop')
|
||||||
|
```
|
||||||
|
|
||||||
|
233168
|
||||||
|
|
||||||
|
|
||||||
|
# A little further analysis renders iteration unnecessary.
|
||||||
|
Consider finding the sum of the positive integers less than or equal to ten.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[10 9 8 7 6 5 4 3 2 1] sum')
|
||||||
|
```
|
||||||
|
|
||||||
|
55
|
||||||
|
|
||||||
|
|
||||||
|
Instead of summing them, [observe](https://en.wikipedia.org/wiki/File:Animated_proof_for_the_formula_giving_the_sum_of_the_first_integers_1%2B2%2B...%2Bn.gif):
|
||||||
|
|
||||||
|
10 9 8 7 6
|
||||||
|
+ 1 2 3 4 5
|
||||||
|
---- -- -- -- --
|
||||||
|
11 11 11 11 11
|
||||||
|
|
||||||
|
11 * 5 = 55
|
||||||
|
|
||||||
|
From the above example we can deduce that the sum of the first N positive integers is:
|
||||||
|
|
||||||
|
(N + 1) * N / 2
|
||||||
|
|
||||||
|
(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.)
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('F == dup ++ * 2 floordiv')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('10 F')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 10 F
|
||||||
|
10 . F
|
||||||
|
10 . dup ++ * 2 floordiv
|
||||||
|
10 10 . ++ * 2 floordiv
|
||||||
|
10 11 . * 2 floordiv
|
||||||
|
110 . 2 floordiv
|
||||||
|
110 2 . floordiv
|
||||||
|
55 .
|
||||||
|
|
||||||
|
|
||||||
|
## Generalizing to Blocks of Terms
|
||||||
|
We can apply the same reasoning to the PE1 problem.
|
||||||
|
|
||||||
|
Between 0 and 990 inclusive there are sixty-six "blocks" of seven terms each, starting with:
|
||||||
|
|
||||||
|
[3 5 6 9 10 12 15]
|
||||||
|
|
||||||
|
And ending with:
|
||||||
|
|
||||||
|
[978 980 981 984 985 987 990]
|
||||||
|
|
||||||
|
If we reverse one of these two blocks and sum pairs...
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
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]]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
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]
|
||||||
|
|
||||||
|
|
||||||
|
(Interesting that the sequence of seven numbers appears again in the rightmost digit of each term.)
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[ 3 5 6 9 10 12 15] reverse [978 980 981 984 985 987 990] zip [sum] map sum')
|
||||||
|
```
|
||||||
|
|
||||||
|
6945
|
||||||
|
|
||||||
|
|
||||||
|
Since there are sixty-six blocks and we are pairing them up, there must be thirty-three pairs, each of which sums to 6945. We also have these additional unpaired terms between 990 and 1000:
|
||||||
|
|
||||||
|
993 995 996 999
|
||||||
|
|
||||||
|
So we can give the "sum of all the multiples of 3 or 5 below 1000" like so:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('6945 33 * [993 995 996 999] cons sum')
|
||||||
|
```
|
||||||
|
|
||||||
|
233168
|
||||||
|
|
||||||
|
|
||||||
|
It's worth noting, I think, that this same reasoning holds for any two numbers $n$ and $m$ the multiples of which we hope to sum. The multiples would have a cycle of differences of length $k$ and so we could compute the sum of $Nk$ multiples as above.
|
||||||
|
|
||||||
|
The sequence of differences will always be a palidrome. Consider an interval spanning the least common multiple of $n$ and $m$:
|
||||||
|
|
||||||
|
| | | | | | | |
|
||||||
|
| | | | |
|
||||||
|
|
||||||
|
Here we have 4 and 7, and you can read off the sequence of differences directly from the diagram: 4 3 1 4 2 2 4 1 3 4.
|
||||||
|
|
||||||
|
Geometrically, the actual values of $n$ and $m$ and their *lcm* don't matter, the pattern they make will always be symmetrical around its midpoint. The same reasoning holds for multiples of more than two numbers.
|
||||||
|
|
||||||
|
# The Simplest Program
|
||||||
|
|
||||||
|
Of course, the simplest joy program for the first Project Euler problem is just:
|
||||||
|
|
||||||
|
PE1 == 233168
|
||||||
|
|
||||||
|
Fin.
|
||||||
|
|
@ -0,0 +1,252 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Preamble"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from notebook_preamble import D, J, V"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### A long trace"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . [23 18] average\n",
|
||||||
|
" [23 18] . average\n",
|
||||||
|
" [23 18] . [sum 1.0 *] [size] cleave /\n",
|
||||||
|
" [23 18] [sum 1.0 *] . [size] cleave /\n",
|
||||||
|
" [23 18] [sum 1.0 *] [size] . cleave /\n",
|
||||||
|
" [23 18] [sum 1.0 *] [size] . [i] app2 [popd] dip /\n",
|
||||||
|
" [23 18] [sum 1.0 *] [size] [i] . app2 [popd] dip /\n",
|
||||||
|
"[23 18] [[sum 1.0 *] [23 18]] [i] . infra first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" [23 18] [sum 1.0 *] . i [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" [23 18] . sum 1.0 * [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" 41 . 1.0 * [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" 41 1.0 . * [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" 41.0 . [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" 41.0 [[23 18]] . swaack first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" [23 18] [41.0] . first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" [23 18] 41.0 . [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" [23 18] 41.0 [[size] [23 18]] . [i] infra first [popd] dip /\n",
|
||||||
|
"[23 18] 41.0 [[size] [23 18]] [i] . infra first [popd] dip /\n",
|
||||||
|
" [23 18] [size] . i [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" [23 18] . size [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" [23 18] . 0 swap [pop ++] step [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" [23 18] 0 . swap [pop ++] step [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 0 [23 18] . [pop ++] step [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 0 [23 18] [pop ++] . step [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 0 23 [pop ++] . i [18] [pop ++] step [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 0 23 . pop ++ [18] [pop ++] step [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 0 . ++ [18] [pop ++] step [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 1 . [18] [pop ++] step [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 1 [18] . [pop ++] step [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 1 [18] [pop ++] . step [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 1 18 [pop ++] . i [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 1 18 . pop ++ [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 1 . ++ [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 2 . [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 2 [41.0 [23 18]] . swaack first [popd] dip /\n",
|
||||||
|
" [23 18] 41.0 [2] . first [popd] dip /\n",
|
||||||
|
" [23 18] 41.0 2 . [popd] dip /\n",
|
||||||
|
" [23 18] 41.0 2 [popd] . dip /\n",
|
||||||
|
" [23 18] 41.0 . popd 2 /\n",
|
||||||
|
" 41.0 . 2 /\n",
|
||||||
|
" 41.0 2 . /\n",
|
||||||
|
" 20.5 . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('[23 18] average')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Replacing `sum` and `size` with \"compiled\" versions.\n",
|
||||||
|
"\n",
|
||||||
|
"Both `sum` and `size` are [catamorphisms](https://en.wikipedia.org/wiki/Catamorphism), they each convert a sequence to a single value."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"Given a quoted sequence of numbers return the sum.\n",
|
||||||
|
"\n",
|
||||||
|
"sum == 0 swap [+] step\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[sum] help')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"0 swap [pop ++] step\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[size] help')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can use \"compiled\" versions (they're not really compiled in this case, they're hand-written in Python) to speed up evaluation and make the trace more readable. The `sum` function is already in the library. It gets shadowed by the definition version above during `initialize()`."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from joy.library import SimpleFunctionWrapper, primitives\n",
|
||||||
|
"from joy.utils.stack import iter_stack\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"@SimpleFunctionWrapper\n",
|
||||||
|
"def size(stack):\n",
|
||||||
|
" '''Return the size of the sequence on the stack.'''\n",
|
||||||
|
" sequence, stack = stack\n",
|
||||||
|
" n = 0\n",
|
||||||
|
" for _ in iter_stack(sequence):\n",
|
||||||
|
" n += 1\n",
|
||||||
|
" return n, stack\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"sum_ = next(p for p in primitives if p.name == 'sum')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now we replace them old versions in the dictionary with the new versions and re-evaluate the expression."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"old_sum, D['sum'] = D['sum'], sum_\n",
|
||||||
|
"old_size, D['size'] = D['size'], size"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"You can see that `size` and `sum` now execute in a single step."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . [23 18] average\n",
|
||||||
|
" [23 18] . average\n",
|
||||||
|
" [23 18] . [sum 1.0 *] [size] cleave /\n",
|
||||||
|
" [23 18] [sum 1.0 *] . [size] cleave /\n",
|
||||||
|
" [23 18] [sum 1.0 *] [size] . cleave /\n",
|
||||||
|
" [23 18] [sum 1.0 *] [size] . [i] app2 [popd] dip /\n",
|
||||||
|
" [23 18] [sum 1.0 *] [size] [i] . app2 [popd] dip /\n",
|
||||||
|
"[23 18] [[sum 1.0 *] [23 18]] [i] . infra first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" [23 18] [sum 1.0 *] . i [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" [23 18] . sum 1.0 * [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" 41 . 1.0 * [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" 41 1.0 . * [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" 41.0 . [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" 41.0 [[23 18]] . swaack first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" [23 18] [41.0] . first [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" [23 18] 41.0 . [[size] [23 18]] [i] infra first [popd] dip /\n",
|
||||||
|
" [23 18] 41.0 [[size] [23 18]] . [i] infra first [popd] dip /\n",
|
||||||
|
"[23 18] 41.0 [[size] [23 18]] [i] . infra first [popd] dip /\n",
|
||||||
|
" [23 18] [size] . i [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" [23 18] . size [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 2 . [41.0 [23 18]] swaack first [popd] dip /\n",
|
||||||
|
" 2 [41.0 [23 18]] . swaack first [popd] dip /\n",
|
||||||
|
" [23 18] 41.0 [2] . first [popd] dip /\n",
|
||||||
|
" [23 18] 41.0 2 . [popd] dip /\n",
|
||||||
|
" [23 18] 41.0 2 [popd] . dip /\n",
|
||||||
|
" [23 18] 41.0 . popd 2 /\n",
|
||||||
|
" 41.0 . 2 /\n",
|
||||||
|
" 41.0 2 . /\n",
|
||||||
|
" 20.5 . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('[23 18] average')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 2",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python2"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 2
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython2",
|
||||||
|
"version": "2.7.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,149 @@
|
||||||
|
|
||||||
|
### Preamble
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from notebook_preamble import D, J, V
|
||||||
|
```
|
||||||
|
|
||||||
|
### A long trace
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('[23 18] average')
|
||||||
|
```
|
||||||
|
|
||||||
|
. [23 18] average
|
||||||
|
[23 18] . average
|
||||||
|
[23 18] . [sum 1.0 *] [size] cleave /
|
||||||
|
[23 18] [sum 1.0 *] . [size] cleave /
|
||||||
|
[23 18] [sum 1.0 *] [size] . cleave /
|
||||||
|
[23 18] [sum 1.0 *] [size] . [i] app2 [popd] dip /
|
||||||
|
[23 18] [sum 1.0 *] [size] [i] . app2 [popd] dip /
|
||||||
|
[23 18] [[sum 1.0 *] [23 18]] [i] . infra first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
[23 18] [sum 1.0 *] . i [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
[23 18] . sum 1.0 * [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
41 . 1.0 * [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
41 1.0 . * [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
41.0 . [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
41.0 [[23 18]] . swaack first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
[23 18] [41.0] . first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
[23 18] 41.0 . [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
[23 18] 41.0 [[size] [23 18]] . [i] infra first [popd] dip /
|
||||||
|
[23 18] 41.0 [[size] [23 18]] [i] . infra first [popd] dip /
|
||||||
|
[23 18] [size] . i [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
[23 18] . size [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
[23 18] . 0 swap [pop ++] step [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
[23 18] 0 . swap [pop ++] step [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
0 [23 18] . [pop ++] step [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
0 [23 18] [pop ++] . step [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
0 23 [pop ++] . i [18] [pop ++] step [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
0 23 . pop ++ [18] [pop ++] step [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
0 . ++ [18] [pop ++] step [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
1 . [18] [pop ++] step [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
1 [18] . [pop ++] step [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
1 [18] [pop ++] . step [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
1 18 [pop ++] . i [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
1 18 . pop ++ [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
1 . ++ [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
2 . [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
2 [41.0 [23 18]] . swaack first [popd] dip /
|
||||||
|
[23 18] 41.0 [2] . first [popd] dip /
|
||||||
|
[23 18] 41.0 2 . [popd] dip /
|
||||||
|
[23 18] 41.0 2 [popd] . dip /
|
||||||
|
[23 18] 41.0 . popd 2 /
|
||||||
|
41.0 . 2 /
|
||||||
|
41.0 2 . /
|
||||||
|
20.5 .
|
||||||
|
|
||||||
|
|
||||||
|
### Replacing `sum` and `size` with "compiled" versions.
|
||||||
|
|
||||||
|
Both `sum` and `size` are [catamorphisms](https://en.wikipedia.org/wiki/Catamorphism), they each convert a sequence to a single value.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[sum] help')
|
||||||
|
```
|
||||||
|
|
||||||
|
Given a quoted sequence of numbers return the sum.
|
||||||
|
|
||||||
|
sum == 0 swap [+] step
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[size] help')
|
||||||
|
```
|
||||||
|
|
||||||
|
0 swap [pop ++] step
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
We can use "compiled" versions (they're not really compiled in this case, they're hand-written in Python) to speed up evaluation and make the trace more readable. The `sum` function is already in the library. It gets shadowed by the definition version above during `initialize()`.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from joy.library import SimpleFunctionWrapper, primitives
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
sum_ = next(p for p in primitives if p.name == 'sum')
|
||||||
|
```
|
||||||
|
|
||||||
|
Now we replace them old versions in the dictionary with the new versions and re-evaluate the expression.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
old_sum, D['sum'] = D['sum'], sum_
|
||||||
|
old_size, D['size'] = D['size'], size
|
||||||
|
```
|
||||||
|
|
||||||
|
You can see that `size` and `sum` now execute in a single step.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('[23 18] average')
|
||||||
|
```
|
||||||
|
|
||||||
|
. [23 18] average
|
||||||
|
[23 18] . average
|
||||||
|
[23 18] . [sum 1.0 *] [size] cleave /
|
||||||
|
[23 18] [sum 1.0 *] . [size] cleave /
|
||||||
|
[23 18] [sum 1.0 *] [size] . cleave /
|
||||||
|
[23 18] [sum 1.0 *] [size] . [i] app2 [popd] dip /
|
||||||
|
[23 18] [sum 1.0 *] [size] [i] . app2 [popd] dip /
|
||||||
|
[23 18] [[sum 1.0 *] [23 18]] [i] . infra first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
[23 18] [sum 1.0 *] . i [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
[23 18] . sum 1.0 * [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
41 . 1.0 * [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
41 1.0 . * [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
41.0 . [[23 18]] swaack first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
41.0 [[23 18]] . swaack first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
[23 18] [41.0] . first [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
[23 18] 41.0 . [[size] [23 18]] [i] infra first [popd] dip /
|
||||||
|
[23 18] 41.0 [[size] [23 18]] . [i] infra first [popd] dip /
|
||||||
|
[23 18] 41.0 [[size] [23 18]] [i] . infra first [popd] dip /
|
||||||
|
[23 18] [size] . i [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
[23 18] . size [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
2 . [41.0 [23 18]] swaack first [popd] dip /
|
||||||
|
2 [41.0 [23 18]] . swaack first [popd] dip /
|
||||||
|
[23 18] 41.0 [2] . first [popd] dip /
|
||||||
|
[23 18] 41.0 2 . [popd] dip /
|
||||||
|
[23 18] 41.0 2 [popd] . dip /
|
||||||
|
[23 18] 41.0 . popd 2 /
|
||||||
|
41.0 . 2 /
|
||||||
|
41.0 2 . /
|
||||||
|
20.5 .
|
||||||
|
|
||||||
|
|
@ -0,0 +1,455 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Advent of Code 2017\n",
|
||||||
|
"\n",
|
||||||
|
"## December 1st\n",
|
||||||
|
"\n",
|
||||||
|
"\\[Given\\] a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list.\n",
|
||||||
|
"\n",
|
||||||
|
"For example:\n",
|
||||||
|
"\n",
|
||||||
|
"* 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.\n",
|
||||||
|
"* 1111 produces 4 because each digit (all 1) matches the next.\n",
|
||||||
|
"* 1234 produces 0 because no digit matches the next.\n",
|
||||||
|
"* 91212129 produces 9 because the only digit that matches the next one is the last digit, 9."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from notebook_preamble import J, V, define"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"I'll assume the input is a Joy sequence of integers (as opposed to a string or something else.)\n",
|
||||||
|
"\n",
|
||||||
|
"We might proceed by creating a word that makes a copy of the sequence with the first item moved to the last, and zips it with the original to make a list of pairs, and a another word that adds (one of) each pair to a total if the pair matches.\n",
|
||||||
|
"\n",
|
||||||
|
" AoC2017.1 == pair_up total_matches\n",
|
||||||
|
"\n",
|
||||||
|
"Let's derive `pair_up`:\n",
|
||||||
|
"\n",
|
||||||
|
" [a b c] pair_up\n",
|
||||||
|
" -------------------------\n",
|
||||||
|
" [[a b] [b c] [c a]]\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Straightforward (although the order of each pair is reversed, due to the way `zip` works, but it doesn't matter for this program):\n",
|
||||||
|
"\n",
|
||||||
|
" [a b c] dup\n",
|
||||||
|
" [a b c] [a b c] uncons swap\n",
|
||||||
|
" [a b c] [b c] a unit concat\n",
|
||||||
|
" [a b c] [b c a] zip\n",
|
||||||
|
" [[b a] [c b] [a c]]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('pair_up == dup uncons swap unit concat zip')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[2 1] [3 2] [1 3]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 2 3] pair_up')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": true
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[2 1] [2 2] [3 2] [1 3]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 2 2 3] pair_up')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now we need to derive `total_matches`. It will be a `step` function:\n",
|
||||||
|
"\n",
|
||||||
|
" total_matches == 0 swap [F] step\n",
|
||||||
|
"\n",
|
||||||
|
"Where `F` will have the pair to work with, and it will basically be a `branch` or `ifte`.\n",
|
||||||
|
"\n",
|
||||||
|
" total [n m] F\n",
|
||||||
|
"\n",
|
||||||
|
"It will probably be easier to write if we dequote the pair:\n",
|
||||||
|
"\n",
|
||||||
|
" total [n m] i F′\n",
|
||||||
|
" ----------------------\n",
|
||||||
|
" total n m F′\n",
|
||||||
|
"\n",
|
||||||
|
"Now `F′` becomes just:\n",
|
||||||
|
"\n",
|
||||||
|
" total n m [=] [pop +] [popop] ifte\n",
|
||||||
|
"\n",
|
||||||
|
"So:\n",
|
||||||
|
"\n",
|
||||||
|
" F == i [=] [pop +] [popop] ifte\n",
|
||||||
|
"\n",
|
||||||
|
"And thus:\n",
|
||||||
|
"\n",
|
||||||
|
" total_matches == 0 swap [i [=] [pop +] [popop] ifte] step"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('total_matches == 0 swap [i [=] [pop +] [popop] ifte] step')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"0\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 2 3] pair_up total_matches')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"2\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 2 2 3] pair_up total_matches')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now we can define our main program and evaluate it on the examples."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('AoC2017.1 == pair_up total_matches')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 1 2 2] AoC2017.1')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"4\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 1 1 1] AoC2017.1')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"0\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 2 3 4] AoC2017.1')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 12,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": false
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"9\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[9 1 2 1 2 1 2 9] AoC2017.1')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 13,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": false
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"9\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[9 1 2 1 2 1 2 9] AoC2017.1')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
" pair_up == dup uncons swap unit concat zip\n",
|
||||||
|
" total_matches == 0 swap [i [=] [pop +] [popop] ifte] step\n",
|
||||||
|
"\n",
|
||||||
|
" AoC2017.1 == pair_up total_matches"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now the paired digit is \"halfway\" round.\n",
|
||||||
|
"\n",
|
||||||
|
" [a b c d] dup size 2 / [drop] [take reverse] cleave concat zip"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 14,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[[3 1] [4 2] [1 3] [2 4]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 2 3 4] dup size 2 / [drop] [take reverse] cleave concat zip')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"I realized that each pair is repeated..."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 15,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1 2 3 4] [[1 3] [2 4]]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 2 3 4] dup size 2 / [drop] [take reverse] cleave zip')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 16,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('AoC2017.1.extra == dup size 2 / [drop] [take reverse] cleave zip swap pop total_matches 2 *')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 17,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"6\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 2 1 2] AoC2017.1.extra')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 18,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"0\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 2 2 1] AoC2017.1.extra')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 19,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"4\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 2 3 4 2 5] AoC2017.1.extra')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Refactor FTW\n",
|
||||||
|
"\n",
|
||||||
|
"With Joy a great deal of the heuristics from Forth programming carry over nicely. For example, refactoring into small, well-scoped commands with mnemonic names...\n",
|
||||||
|
"\n",
|
||||||
|
" rotate_seq == uncons swap unit concat\n",
|
||||||
|
" pair_up == dup rotate_seq zip\n",
|
||||||
|
" add_if_match == [=] [pop +] [popop] ifte\n",
|
||||||
|
" total_matches == [i add_if_match] step_zero\n",
|
||||||
|
"\n",
|
||||||
|
" AoC2017.1 == pair_up total_matches\n",
|
||||||
|
"\n",
|
||||||
|
" half_of_size == dup size 2 /\n",
|
||||||
|
" split_at == [drop] [take reverse] cleave\n",
|
||||||
|
" pair_up.extra == half_of_size split_at zip swap pop\n",
|
||||||
|
"\n",
|
||||||
|
" AoC2017.1.extra == pair_up.extra total_matches 2 *\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 2",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python2"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 2
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython2",
|
||||||
|
"version": "2.7.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,228 @@
|
||||||
|
|
||||||
|
# Advent of Code 2017
|
||||||
|
|
||||||
|
## December 1st
|
||||||
|
|
||||||
|
\[Given\] a sequence of digits (your puzzle input) and find the sum of all digits that match the next digit in the list. The list is circular, so the digit after the last digit is the first digit in the list.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
* 1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.
|
||||||
|
* 1111 produces 4 because each digit (all 1) matches the next.
|
||||||
|
* 1234 produces 0 because no digit matches the next.
|
||||||
|
* 91212129 produces 9 because the only digit that matches the next one is the last digit, 9.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from notebook_preamble import J, V, define
|
||||||
|
```
|
||||||
|
|
||||||
|
I'll assume the input is a Joy sequence of integers (as opposed to a string or something else.)
|
||||||
|
|
||||||
|
We might proceed by creating a word that makes a copy of the sequence with the first item moved to the last, and zips it with the original to make a list of pairs, and a another word that adds (one of) each pair to a total if the pair matches.
|
||||||
|
|
||||||
|
AoC2017.1 == pair_up total_matches
|
||||||
|
|
||||||
|
Let's derive `pair_up`:
|
||||||
|
|
||||||
|
[a b c] pair_up
|
||||||
|
-------------------------
|
||||||
|
[[a b] [b c] [c a]]
|
||||||
|
|
||||||
|
|
||||||
|
Straightforward (although the order of each pair is reversed, due to the way `zip` works, but it doesn't matter for this program):
|
||||||
|
|
||||||
|
[a b c] dup
|
||||||
|
[a b c] [a b c] uncons swap
|
||||||
|
[a b c] [b c] a unit concat
|
||||||
|
[a b c] [b c a] zip
|
||||||
|
[[b a] [c b] [a c]]
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('pair_up == dup uncons swap unit concat zip')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 2 3] pair_up')
|
||||||
|
```
|
||||||
|
|
||||||
|
[[2 1] [3 2] [1 3]]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 2 2 3] pair_up')
|
||||||
|
```
|
||||||
|
|
||||||
|
[[2 1] [2 2] [3 2] [1 3]]
|
||||||
|
|
||||||
|
|
||||||
|
Now we need to derive `total_matches`. It will be a `step` function:
|
||||||
|
|
||||||
|
total_matches == 0 swap [F] step
|
||||||
|
|
||||||
|
Where `F` will have the pair to work with, and it will basically be a `branch` or `ifte`.
|
||||||
|
|
||||||
|
total [n m] F
|
||||||
|
|
||||||
|
It will probably be easier to write if we dequote the pair:
|
||||||
|
|
||||||
|
total [n m] i F′
|
||||||
|
----------------------
|
||||||
|
total n m F′
|
||||||
|
|
||||||
|
Now `F′` becomes just:
|
||||||
|
|
||||||
|
total n m [=] [pop +] [popop] ifte
|
||||||
|
|
||||||
|
So:
|
||||||
|
|
||||||
|
F == i [=] [pop +] [popop] ifte
|
||||||
|
|
||||||
|
And thus:
|
||||||
|
|
||||||
|
total_matches == 0 swap [i [=] [pop +] [popop] ifte] step
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('total_matches == 0 swap [i [=] [pop +] [popop] ifte] step')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 2 3] pair_up total_matches')
|
||||||
|
```
|
||||||
|
|
||||||
|
0
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 2 2 3] pair_up total_matches')
|
||||||
|
```
|
||||||
|
|
||||||
|
2
|
||||||
|
|
||||||
|
|
||||||
|
Now we can define our main program and evaluate it on the examples.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('AoC2017.1 == pair_up total_matches')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 1 2 2] AoC2017.1')
|
||||||
|
```
|
||||||
|
|
||||||
|
3
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 1 1 1] AoC2017.1')
|
||||||
|
```
|
||||||
|
|
||||||
|
4
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 2 3 4] AoC2017.1')
|
||||||
|
```
|
||||||
|
|
||||||
|
0
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[9 1 2 1 2 1 2 9] AoC2017.1')
|
||||||
|
```
|
||||||
|
|
||||||
|
9
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[9 1 2 1 2 1 2 9] AoC2017.1')
|
||||||
|
```
|
||||||
|
|
||||||
|
9
|
||||||
|
|
||||||
|
|
||||||
|
pair_up == dup uncons swap unit concat zip
|
||||||
|
total_matches == 0 swap [i [=] [pop +] [popop] ifte] step
|
||||||
|
|
||||||
|
AoC2017.1 == pair_up total_matches
|
||||||
|
|
||||||
|
Now the paired digit is "halfway" round.
|
||||||
|
|
||||||
|
[a b c d] dup size 2 / [drop] [take reverse] cleave concat zip
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 2 3 4] dup size 2 / [drop] [take reverse] cleave concat zip')
|
||||||
|
```
|
||||||
|
|
||||||
|
[[3 1] [4 2] [1 3] [2 4]]
|
||||||
|
|
||||||
|
|
||||||
|
I realized that each pair is repeated...
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 2 3 4] dup size 2 / [drop] [take reverse] cleave zip')
|
||||||
|
```
|
||||||
|
|
||||||
|
[1 2 3 4] [[1 3] [2 4]]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('AoC2017.1.extra == dup size 2 / [drop] [take reverse] cleave zip swap pop total_matches 2 *')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 2 1 2] AoC2017.1.extra')
|
||||||
|
```
|
||||||
|
|
||||||
|
6
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 2 2 1] AoC2017.1.extra')
|
||||||
|
```
|
||||||
|
|
||||||
|
0
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 2 3 4 2 5] AoC2017.1.extra')
|
||||||
|
```
|
||||||
|
|
||||||
|
4
|
||||||
|
|
||||||
|
|
||||||
|
# Refactor FTW
|
||||||
|
|
||||||
|
With Joy a great deal of the heuristics from Forth programming carry over nicely. For example, refactoring into small, well-scoped commands with mnemonic names...
|
||||||
|
|
||||||
|
rotate_seq == uncons swap unit concat
|
||||||
|
pair_up == dup rotate_seq zip
|
||||||
|
add_if_match == [=] [pop +] [popop] ifte
|
||||||
|
total_matches == [i add_if_match] step_zero
|
||||||
|
|
||||||
|
AoC2017.1 == pair_up total_matches
|
||||||
|
|
||||||
|
half_of_size == dup size 2 /
|
||||||
|
split_at == [drop] [take reverse] cleave
|
||||||
|
pair_up.extra == half_of_size split_at zip swap pop
|
||||||
|
|
||||||
|
AoC2017.1.extra == pair_up.extra total_matches 2 *
|
||||||
|
|
||||||
|
|
@ -0,0 +1,554 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Advent of Code 2017\n",
|
||||||
|
"\n",
|
||||||
|
"## December 2nd\n",
|
||||||
|
"\n",
|
||||||
|
"For each row, determine the difference between the largest value and the smallest value; the checksum is the sum of all of these differences.\n",
|
||||||
|
"\n",
|
||||||
|
"For example, given the following spreadsheet:\n",
|
||||||
|
"\n",
|
||||||
|
" 5 1 9 5\n",
|
||||||
|
" 7 5 3\n",
|
||||||
|
" 2 4 6 8\n",
|
||||||
|
"\n",
|
||||||
|
"* The first row's largest and smallest values are 9 and 1, and their difference is 8.\n",
|
||||||
|
"* The second row's largest and smallest values are 7 and 3, and their difference is 4.\n",
|
||||||
|
"* The third row's difference is 6.\n",
|
||||||
|
"\n",
|
||||||
|
"In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from notebook_preamble import J, V, define"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"I'll assume the input is a Joy sequence of sequences of integers.\n",
|
||||||
|
"\n",
|
||||||
|
" [[5 1 9 5]\n",
|
||||||
|
" [7 5 3]\n",
|
||||||
|
" [2 4 6 8]]\n",
|
||||||
|
"\n",
|
||||||
|
"So, obviously, the initial form will be a `step` function:\n",
|
||||||
|
"\n",
|
||||||
|
" AoC2017.2 == 0 swap [F +] step"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This function `F` must get the `max` and `min` of a row of numbers and subtract. We can define a helper function `maxmin` which does this:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('maxmin == [max] [min] cleave')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3 1\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 2 3] maxmin')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Then `F` just does that then subtracts the min from the max:\n",
|
||||||
|
"\n",
|
||||||
|
" F == maxmin -\n",
|
||||||
|
"\n",
|
||||||
|
"So:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('AoC2017.2 == [maxmin - +] step_zero')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"18\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('''\n",
|
||||||
|
"\n",
|
||||||
|
"[[5 1 9 5]\n",
|
||||||
|
" [7 5 3]\n",
|
||||||
|
" [2 4 6 8]] AoC2017.2\n",
|
||||||
|
"\n",
|
||||||
|
"''')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"...find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result.\n",
|
||||||
|
"\n",
|
||||||
|
"For example, given the following spreadsheet:\n",
|
||||||
|
"\n",
|
||||||
|
" 5 9 2 8\n",
|
||||||
|
" 9 4 7 3\n",
|
||||||
|
" 3 8 6 5\n",
|
||||||
|
"\n",
|
||||||
|
"* In the first row, the only two numbers that evenly divide are 8 and 2; the result of this division is 4.\n",
|
||||||
|
"* In the second row, the two numbers are 9 and 3; the result is 3.\n",
|
||||||
|
"* In the third row, the result is 2.\n",
|
||||||
|
"\n",
|
||||||
|
"In this example, the sum of the results would be 4 + 3 + 2 = 9.\n",
|
||||||
|
"\n",
|
||||||
|
"What is the sum of each row's result in your puzzle input?"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[9 8 5 2]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[5 9 2 8] sort reverse')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[8 5 2] [9 divmod] [8 5 2]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[9 8 5 2] uncons [swap [divmod] cons] dupdip')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"\n",
|
||||||
|
" [9 8 5 2] uncons [swap [divmod] cons F] dupdip G\n",
|
||||||
|
" [8 5 2] [9 divmod] F [8 5 2] G\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . [8 5 2] [9 divmod] [uncons swap] dip dup [i not] dip\n",
|
||||||
|
" [8 5 2] . [9 divmod] [uncons swap] dip dup [i not] dip\n",
|
||||||
|
" [8 5 2] [9 divmod] . [uncons swap] dip dup [i not] dip\n",
|
||||||
|
" [8 5 2] [9 divmod] [uncons swap] . dip dup [i not] dip\n",
|
||||||
|
" [8 5 2] . uncons swap [9 divmod] dup [i not] dip\n",
|
||||||
|
" 8 [5 2] . swap [9 divmod] dup [i not] dip\n",
|
||||||
|
" [5 2] 8 . [9 divmod] dup [i not] dip\n",
|
||||||
|
" [5 2] 8 [9 divmod] . dup [i not] dip\n",
|
||||||
|
" [5 2] 8 [9 divmod] [9 divmod] . [i not] dip\n",
|
||||||
|
"[5 2] 8 [9 divmod] [9 divmod] [i not] . dip\n",
|
||||||
|
" [5 2] 8 [9 divmod] . i not [9 divmod]\n",
|
||||||
|
" [5 2] 8 . 9 divmod not [9 divmod]\n",
|
||||||
|
" [5 2] 8 9 . divmod not [9 divmod]\n",
|
||||||
|
" [5 2] 1 1 . not [9 divmod]\n",
|
||||||
|
" [5 2] 1 False . [9 divmod]\n",
|
||||||
|
" [5 2] 1 False [9 divmod] . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('[8 5 2] [9 divmod] [uncons swap] dip dup [i not] dip')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Tricky\n",
|
||||||
|
"\n",
|
||||||
|
"Let's think.\n",
|
||||||
|
"\n",
|
||||||
|
"Given a *sorted* sequence (from highest to lowest) we want to \n",
|
||||||
|
"* for head, tail in sequence\n",
|
||||||
|
" * for term in tail:\n",
|
||||||
|
" * check if the head % term == 0\n",
|
||||||
|
" * if so compute head / term and terminate loop\n",
|
||||||
|
" * else continue"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### So we want a `loop` I think\n",
|
||||||
|
"\n",
|
||||||
|
" [a b c d] True [Q] loop\n",
|
||||||
|
" [a b c d] Q [Q] loop\n",
|
||||||
|
"\n",
|
||||||
|
"`Q` should either leave the result and False, or the `rest` and True.\n",
|
||||||
|
"\n",
|
||||||
|
" [a b c d] Q\n",
|
||||||
|
" -----------------\n",
|
||||||
|
" result 0\n",
|
||||||
|
"\n",
|
||||||
|
" [a b c d] Q\n",
|
||||||
|
" -----------------\n",
|
||||||
|
" [b c d] 1"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This suggests that `Q` should start with:\n",
|
||||||
|
"\n",
|
||||||
|
" [a b c d] uncons dup roll<\n",
|
||||||
|
" [b c d] [b c d] a\n",
|
||||||
|
"\n",
|
||||||
|
"Now we just have to `pop` it if we don't need it.\n",
|
||||||
|
"\n",
|
||||||
|
" [b c d] [b c d] a [P] [T] [cons] app2 popdd [E] primrec\n",
|
||||||
|
" [b c d] [b c d] [a P] [a T] [E] primrec\n",
|
||||||
|
"\n",
|
||||||
|
"-------------------\n",
|
||||||
|
"\n",
|
||||||
|
" w/ Q == [% not] [T] [F] primrec\n",
|
||||||
|
"\n",
|
||||||
|
" [a b c d] uncons\n",
|
||||||
|
" a [b c d] tuck\n",
|
||||||
|
" [b c d] a [b c d] uncons\n",
|
||||||
|
" [b c d] a b [c d] roll>\n",
|
||||||
|
" [b c d] [c d] a b Q\n",
|
||||||
|
" [b c d] [c d] a b [% not] [T] [F] primrec\n",
|
||||||
|
"\n",
|
||||||
|
" [b c d] [c d] a b T\n",
|
||||||
|
" [b c d] [c d] a b / roll> popop 0\n",
|
||||||
|
"\n",
|
||||||
|
" [b c d] [c d] a b F Q\n",
|
||||||
|
" [b c d] [c d] a b pop swap uncons ... Q\n",
|
||||||
|
" [b c d] [c d] a swap uncons ... Q\n",
|
||||||
|
" [b c d] a [c d] uncons ... Q\n",
|
||||||
|
" [b c d] a c [d] roll> Q\n",
|
||||||
|
" [b c d] [d] a c Q\n",
|
||||||
|
"\n",
|
||||||
|
" Q == [% not] [/ roll> popop 0] [pop swap uncons roll>] primrec\n",
|
||||||
|
" \n",
|
||||||
|
" uncons tuck uncons roll> Q"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[8 5 3 2] [9 swap] [9 % not]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[8 5 3 2] 9 [swap] [% not] [cons] app2 popdd')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"-------------------\n",
|
||||||
|
"\n",
|
||||||
|
" [a b c d] uncons\n",
|
||||||
|
" a [b c d] tuck\n",
|
||||||
|
" [b c d] a [b c d] [not] [popop 1] [Q] ifte\n",
|
||||||
|
"\n",
|
||||||
|
" [b c d] a [] popop 1\n",
|
||||||
|
" [b c d] 1\n",
|
||||||
|
"\n",
|
||||||
|
" [b c d] a [b c d] Q \n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
" a [...] Q\n",
|
||||||
|
" ---------------\n",
|
||||||
|
" result 0\n",
|
||||||
|
"\n",
|
||||||
|
" a [...] Q\n",
|
||||||
|
" ---------------\n",
|
||||||
|
" 1\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
" w/ Q == [first % not] [first / 0] [rest [not] [popop 1]] [ifte]\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
" a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]\n",
|
||||||
|
" a [b c d] first % not\n",
|
||||||
|
" a b % not\n",
|
||||||
|
" a%b not\n",
|
||||||
|
" bool(a%b)\n",
|
||||||
|
"\n",
|
||||||
|
" a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]\n",
|
||||||
|
" a [b c d] first / 0\n",
|
||||||
|
" a b / 0\n",
|
||||||
|
" a/b 0\n",
|
||||||
|
"\n",
|
||||||
|
" a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]\n",
|
||||||
|
" a [b c d] rest [not] [popop 1] [Q] ifte\n",
|
||||||
|
" a [c d] [not] [popop 1] [Q] ifte\n",
|
||||||
|
" a [c d] [not] [popop 1] [Q] ifte\n",
|
||||||
|
"\n",
|
||||||
|
" a [c d] [not] [popop 1] [Q] ifte\n",
|
||||||
|
" a [c d] not\n",
|
||||||
|
"\n",
|
||||||
|
" a [] popop 1\n",
|
||||||
|
" 1\n",
|
||||||
|
"\n",
|
||||||
|
" a [c d] Q\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
" uncons tuck [first % not] [first / 0] [rest [not] [popop 1]] [ifte]\n",
|
||||||
|
" \n",
|
||||||
|
" \n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### I finally sat down with a piece of paper and blocked it out.\n",
|
||||||
|
"\n",
|
||||||
|
"First, I made a function `G` that expects a number and a sequence of candidates and return the result or zero:\n",
|
||||||
|
"\n",
|
||||||
|
" n [...] G\n",
|
||||||
|
" ---------------\n",
|
||||||
|
" result\n",
|
||||||
|
"\n",
|
||||||
|
" n [...] G\n",
|
||||||
|
" ---------------\n",
|
||||||
|
" 0\n",
|
||||||
|
"\n",
|
||||||
|
"It's a recursive function that conditionally executes the recursive part of its recursive branch\n",
|
||||||
|
"\n",
|
||||||
|
" [Pg] [E] [R1 [Pi] [T]] [ifte] genrec\n",
|
||||||
|
"\n",
|
||||||
|
"The recursive branch is the else-part of the inner `ifte`:\n",
|
||||||
|
"\n",
|
||||||
|
" G == [Pg] [E] [R1 [Pi] [T]] [ifte] genrec\n",
|
||||||
|
" == [Pg] [E] [R1 [Pi] [T] [G] ifte] ifte\n",
|
||||||
|
"\n",
|
||||||
|
"But this is in hindsight. Going forward I derived:\n",
|
||||||
|
"\n",
|
||||||
|
" G == [first % not]\n",
|
||||||
|
" [first /]\n",
|
||||||
|
" [rest [not] [popop 0]]\n",
|
||||||
|
" [ifte] genrec\n",
|
||||||
|
"\n",
|
||||||
|
"The predicate detects if the `n` can be evenly divided by the `first` item in the list. If so, the then-part returns the result. Otherwise, we have:\n",
|
||||||
|
"\n",
|
||||||
|
" n [m ...] rest [not] [popop 0] [G] ifte\n",
|
||||||
|
" n [...] [not] [popop 0] [G] ifte\n",
|
||||||
|
"\n",
|
||||||
|
"This `ifte` guards against empty sequences and returns zero in that case, otherwise it executes `G`."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('G == [first % not] [first /] [rest [not] [popop 0]] [ifte] genrec')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now we need a word that uses `G` on each (head, tail) pair of a sequence until it finds a (non-zero) result. It's going to be designed to work on a stack that has some candidate `n`, a sequence of possible divisors, and a result that is zero to signal to continue (a non-zero value implies that it is the discovered result):\n",
|
||||||
|
"\n",
|
||||||
|
" n [...] p find-result\n",
|
||||||
|
" ---------------------------\n",
|
||||||
|
" result\n",
|
||||||
|
"\n",
|
||||||
|
"It applies `G` using `nullary` because if it fails with one candidate it needs the list to get the next one (the list is otherwise consumed by `G`.)\n",
|
||||||
|
"\n",
|
||||||
|
" find-result == [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec\n",
|
||||||
|
"\n",
|
||||||
|
" n [...] p [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec\n",
|
||||||
|
"\n",
|
||||||
|
"The base-case is trivial, return the (non-zero) result. The recursive branch...\n",
|
||||||
|
"\n",
|
||||||
|
" n [...] p roll< popop uncons [G] nullary find-result\n",
|
||||||
|
" [...] p n popop uncons [G] nullary find-result\n",
|
||||||
|
" [...] uncons [G] nullary find-result\n",
|
||||||
|
" m [..] [G] nullary find-result\n",
|
||||||
|
" m [..] p find-result\n",
|
||||||
|
"\n",
|
||||||
|
"The puzzle states that the input is well-formed, meaning that we can expect a result before the row sequence empties and so do not need to guard the `uncons`."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('find-result == [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 14,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3.0\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[11 9 8 7 3 2] 0 tuck find-result')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"In order to get the thing started, we need to `sort` the list in descending order, then prime the `find-result` function with a dummy candidate value and zero (\"continue\") flag."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 12,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('prep-row == sort reverse 0 tuck')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now we can define our program."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 13,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('AoC20017.2.extra == [prep-row find-result +] step_zero')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 15,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"9.0\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('''\n",
|
||||||
|
"\n",
|
||||||
|
"[[5 9 2 8]\n",
|
||||||
|
" [9 4 7 3]\n",
|
||||||
|
" [3 8 6 5]] AoC20017.2.extra\n",
|
||||||
|
"\n",
|
||||||
|
"''')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 2",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python2"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 2
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython2",
|
||||||
|
"version": "2.7.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,361 @@
|
||||||
|
|
||||||
|
# Advent of Code 2017
|
||||||
|
|
||||||
|
## December 2nd
|
||||||
|
|
||||||
|
For each row, determine the difference between the largest value and the smallest value; the checksum is the sum of all of these differences.
|
||||||
|
|
||||||
|
For example, given the following spreadsheet:
|
||||||
|
|
||||||
|
5 1 9 5
|
||||||
|
7 5 3
|
||||||
|
2 4 6 8
|
||||||
|
|
||||||
|
* The first row's largest and smallest values are 9 and 1, and their difference is 8.
|
||||||
|
* The second row's largest and smallest values are 7 and 3, and their difference is 4.
|
||||||
|
* The third row's difference is 6.
|
||||||
|
|
||||||
|
In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from notebook_preamble import J, V, define
|
||||||
|
```
|
||||||
|
|
||||||
|
I'll assume the input is a Joy sequence of sequences of integers.
|
||||||
|
|
||||||
|
[[5 1 9 5]
|
||||||
|
[7 5 3]
|
||||||
|
[2 4 6 8]]
|
||||||
|
|
||||||
|
So, obviously, the initial form will be a `step` function:
|
||||||
|
|
||||||
|
AoC2017.2 == 0 swap [F +] step
|
||||||
|
|
||||||
|
This function `F` must get the `max` and `min` of a row of numbers and subtract. We can define a helper function `maxmin` which does this:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('maxmin == [max] [min] cleave')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 2 3] maxmin')
|
||||||
|
```
|
||||||
|
|
||||||
|
3 1
|
||||||
|
|
||||||
|
|
||||||
|
Then `F` just does that then subtracts the min from the max:
|
||||||
|
|
||||||
|
F == maxmin -
|
||||||
|
|
||||||
|
So:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('AoC2017.2 == [maxmin - +] step_zero')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('''
|
||||||
|
|
||||||
|
[[5 1 9 5]
|
||||||
|
[7 5 3]
|
||||||
|
[2 4 6 8]] AoC2017.2
|
||||||
|
|
||||||
|
''')
|
||||||
|
```
|
||||||
|
|
||||||
|
18
|
||||||
|
|
||||||
|
|
||||||
|
...find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result.
|
||||||
|
|
||||||
|
For example, given the following spreadsheet:
|
||||||
|
|
||||||
|
5 9 2 8
|
||||||
|
9 4 7 3
|
||||||
|
3 8 6 5
|
||||||
|
|
||||||
|
* In the first row, the only two numbers that evenly divide are 8 and 2; the result of this division is 4.
|
||||||
|
* In the second row, the two numbers are 9 and 3; the result is 3.
|
||||||
|
* In the third row, the result is 2.
|
||||||
|
|
||||||
|
In this example, the sum of the results would be 4 + 3 + 2 = 9.
|
||||||
|
|
||||||
|
What is the sum of each row's result in your puzzle input?
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[5 9 2 8] sort reverse')
|
||||||
|
```
|
||||||
|
|
||||||
|
[9 8 5 2]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[9 8 5 2] uncons [swap [divmod] cons] dupdip')
|
||||||
|
```
|
||||||
|
|
||||||
|
[8 5 2] [9 divmod] [8 5 2]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
[9 8 5 2] uncons [swap [divmod] cons F] dupdip G
|
||||||
|
[8 5 2] [9 divmod] F [8 5 2] G
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('[8 5 2] [9 divmod] [uncons swap] dip dup [i not] dip')
|
||||||
|
```
|
||||||
|
|
||||||
|
. [8 5 2] [9 divmod] [uncons swap] dip dup [i not] dip
|
||||||
|
[8 5 2] . [9 divmod] [uncons swap] dip dup [i not] dip
|
||||||
|
[8 5 2] [9 divmod] . [uncons swap] dip dup [i not] dip
|
||||||
|
[8 5 2] [9 divmod] [uncons swap] . dip dup [i not] dip
|
||||||
|
[8 5 2] . uncons swap [9 divmod] dup [i not] dip
|
||||||
|
8 [5 2] . swap [9 divmod] dup [i not] dip
|
||||||
|
[5 2] 8 . [9 divmod] dup [i not] dip
|
||||||
|
[5 2] 8 [9 divmod] . dup [i not] dip
|
||||||
|
[5 2] 8 [9 divmod] [9 divmod] . [i not] dip
|
||||||
|
[5 2] 8 [9 divmod] [9 divmod] [i not] . dip
|
||||||
|
[5 2] 8 [9 divmod] . i not [9 divmod]
|
||||||
|
[5 2] 8 . 9 divmod not [9 divmod]
|
||||||
|
[5 2] 8 9 . divmod not [9 divmod]
|
||||||
|
[5 2] 1 1 . not [9 divmod]
|
||||||
|
[5 2] 1 False . [9 divmod]
|
||||||
|
[5 2] 1 False [9 divmod] .
|
||||||
|
|
||||||
|
|
||||||
|
## Tricky
|
||||||
|
|
||||||
|
Let's think.
|
||||||
|
|
||||||
|
Given a *sorted* sequence (from highest to lowest) we want to
|
||||||
|
* for head, tail in sequence
|
||||||
|
* for term in tail:
|
||||||
|
* check if the head % term == 0
|
||||||
|
* if so compute head / term and terminate loop
|
||||||
|
* else continue
|
||||||
|
|
||||||
|
### So we want a `loop` I think
|
||||||
|
|
||||||
|
[a b c d] True [Q] loop
|
||||||
|
[a b c d] Q [Q] loop
|
||||||
|
|
||||||
|
`Q` should either leave the result and False, or the `rest` and True.
|
||||||
|
|
||||||
|
[a b c d] Q
|
||||||
|
-----------------
|
||||||
|
result 0
|
||||||
|
|
||||||
|
[a b c d] Q
|
||||||
|
-----------------
|
||||||
|
[b c d] 1
|
||||||
|
|
||||||
|
This suggests that `Q` should start with:
|
||||||
|
|
||||||
|
[a b c d] uncons dup roll<
|
||||||
|
[b c d] [b c d] a
|
||||||
|
|
||||||
|
Now we just have to `pop` it if we don't need it.
|
||||||
|
|
||||||
|
[b c d] [b c d] a [P] [T] [cons] app2 popdd [E] primrec
|
||||||
|
[b c d] [b c d] [a P] [a T] [E] primrec
|
||||||
|
|
||||||
|
-------------------
|
||||||
|
|
||||||
|
w/ Q == [% not] [T] [F] primrec
|
||||||
|
|
||||||
|
[a b c d] uncons
|
||||||
|
a [b c d] tuck
|
||||||
|
[b c d] a [b c d] uncons
|
||||||
|
[b c d] a b [c d] roll>
|
||||||
|
[b c d] [c d] a b Q
|
||||||
|
[b c d] [c d] a b [% not] [T] [F] primrec
|
||||||
|
|
||||||
|
[b c d] [c d] a b T
|
||||||
|
[b c d] [c d] a b / roll> popop 0
|
||||||
|
|
||||||
|
[b c d] [c d] a b F Q
|
||||||
|
[b c d] [c d] a b pop swap uncons ... Q
|
||||||
|
[b c d] [c d] a swap uncons ... Q
|
||||||
|
[b c d] a [c d] uncons ... Q
|
||||||
|
[b c d] a c [d] roll> Q
|
||||||
|
[b c d] [d] a c Q
|
||||||
|
|
||||||
|
Q == [% not] [/ roll> popop 0] [pop swap uncons roll>] primrec
|
||||||
|
|
||||||
|
uncons tuck uncons roll> Q
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[8 5 3 2] 9 [swap] [% not] [cons] app2 popdd')
|
||||||
|
```
|
||||||
|
|
||||||
|
[8 5 3 2] [9 swap] [9 % not]
|
||||||
|
|
||||||
|
|
||||||
|
-------------------
|
||||||
|
|
||||||
|
[a b c d] uncons
|
||||||
|
a [b c d] tuck
|
||||||
|
[b c d] a [b c d] [not] [popop 1] [Q] ifte
|
||||||
|
|
||||||
|
[b c d] a [] popop 1
|
||||||
|
[b c d] 1
|
||||||
|
|
||||||
|
[b c d] a [b c d] Q
|
||||||
|
|
||||||
|
|
||||||
|
a [...] Q
|
||||||
|
---------------
|
||||||
|
result 0
|
||||||
|
|
||||||
|
a [...] Q
|
||||||
|
---------------
|
||||||
|
1
|
||||||
|
|
||||||
|
|
||||||
|
w/ Q == [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||||
|
a [b c d] first % not
|
||||||
|
a b % not
|
||||||
|
a%b not
|
||||||
|
bool(a%b)
|
||||||
|
|
||||||
|
a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||||
|
a [b c d] first / 0
|
||||||
|
a b / 0
|
||||||
|
a/b 0
|
||||||
|
|
||||||
|
a [b c d] [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||||
|
a [b c d] rest [not] [popop 1] [Q] ifte
|
||||||
|
a [c d] [not] [popop 1] [Q] ifte
|
||||||
|
a [c d] [not] [popop 1] [Q] ifte
|
||||||
|
|
||||||
|
a [c d] [not] [popop 1] [Q] ifte
|
||||||
|
a [c d] not
|
||||||
|
|
||||||
|
a [] popop 1
|
||||||
|
1
|
||||||
|
|
||||||
|
a [c d] Q
|
||||||
|
|
||||||
|
|
||||||
|
uncons tuck [first % not] [first / 0] [rest [not] [popop 1]] [ifte]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### I finally sat down with a piece of paper and blocked it out.
|
||||||
|
|
||||||
|
First, I made a function `G` that expects a number and a sequence of candidates and return the result or zero:
|
||||||
|
|
||||||
|
n [...] G
|
||||||
|
---------------
|
||||||
|
result
|
||||||
|
|
||||||
|
n [...] G
|
||||||
|
---------------
|
||||||
|
0
|
||||||
|
|
||||||
|
It's a recursive function that conditionally executes the recursive part of its recursive branch
|
||||||
|
|
||||||
|
[Pg] [E] [R1 [Pi] [T]] [ifte] genrec
|
||||||
|
|
||||||
|
The recursive branch is the else-part of the inner `ifte`:
|
||||||
|
|
||||||
|
G == [Pg] [E] [R1 [Pi] [T]] [ifte] genrec
|
||||||
|
== [Pg] [E] [R1 [Pi] [T] [G] ifte] ifte
|
||||||
|
|
||||||
|
But this is in hindsight. Going forward I derived:
|
||||||
|
|
||||||
|
G == [first % not]
|
||||||
|
[first /]
|
||||||
|
[rest [not] [popop 0]]
|
||||||
|
[ifte] genrec
|
||||||
|
|
||||||
|
The predicate detects if the `n` can be evenly divided by the `first` item in the list. If so, the then-part returns the result. Otherwise, we have:
|
||||||
|
|
||||||
|
n [m ...] rest [not] [popop 0] [G] ifte
|
||||||
|
n [...] [not] [popop 0] [G] ifte
|
||||||
|
|
||||||
|
This `ifte` guards against empty sequences and returns zero in that case, otherwise it executes `G`.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('G == [first % not] [first /] [rest [not] [popop 0]] [ifte] genrec')
|
||||||
|
```
|
||||||
|
|
||||||
|
Now we need a word that uses `G` on each (head, tail) pair of a sequence until it finds a (non-zero) result. It's going to be designed to work on a stack that has some candidate `n`, a sequence of possible divisors, and a result that is zero to signal to continue (a non-zero value implies that it is the discovered result):
|
||||||
|
|
||||||
|
n [...] p find-result
|
||||||
|
---------------------------
|
||||||
|
result
|
||||||
|
|
||||||
|
It applies `G` using `nullary` because if it fails with one candidate it needs the list to get the next one (the list is otherwise consumed by `G`.)
|
||||||
|
|
||||||
|
find-result == [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec
|
||||||
|
|
||||||
|
n [...] p [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec
|
||||||
|
|
||||||
|
The base-case is trivial, return the (non-zero) result. The recursive branch...
|
||||||
|
|
||||||
|
n [...] p roll< popop uncons [G] nullary find-result
|
||||||
|
[...] p n popop uncons [G] nullary find-result
|
||||||
|
[...] uncons [G] nullary find-result
|
||||||
|
m [..] [G] nullary find-result
|
||||||
|
m [..] p find-result
|
||||||
|
|
||||||
|
The puzzle states that the input is well-formed, meaning that we can expect a result before the row sequence empties and so do not need to guard the `uncons`.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('find-result == [0 >] [roll> popop] [roll< popop uncons [G] nullary] primrec')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[11 9 8 7 3 2] 0 tuck find-result')
|
||||||
|
```
|
||||||
|
|
||||||
|
3.0
|
||||||
|
|
||||||
|
|
||||||
|
In order to get the thing started, we need to `sort` the list in descending order, then prime the `find-result` function with a dummy candidate value and zero ("continue") flag.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('prep-row == sort reverse 0 tuck')
|
||||||
|
```
|
||||||
|
|
||||||
|
Now we can define our program.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('AoC20017.2.extra == [prep-row find-result +] step_zero')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('''
|
||||||
|
|
||||||
|
[[5 9 2 8]
|
||||||
|
[9 4 7 3]
|
||||||
|
[3 8 6 5]] AoC20017.2.extra
|
||||||
|
|
||||||
|
''')
|
||||||
|
```
|
||||||
|
|
||||||
|
9.0
|
||||||
|
|
||||||
|
|
@ -0,0 +1,843 @@
|
||||||
|
|
||||||
|
# Advent of Code 2017
|
||||||
|
|
||||||
|
## December 3rd
|
||||||
|
|
||||||
|
You come across an experimental new kind of memory stored on an infinite two-dimensional grid.
|
||||||
|
|
||||||
|
Each square on the grid is allocated in a spiral pattern starting at a location marked 1 and then counting up while spiraling outward. For example, the first few squares are allocated like this:
|
||||||
|
|
||||||
|
17 16 15 14 13
|
||||||
|
18 5 4 3 12
|
||||||
|
19 6 1 2 11
|
||||||
|
20 7 8 9 10
|
||||||
|
21 22 23---> ...
|
||||||
|
|
||||||
|
While this is very space-efficient (no squares are skipped), requested data must be carried back to square 1 (the location of the only access port for this memory system) by programs that can only move up, down, left, or right. They always take the shortest path: the Manhattan Distance between the location of the data and square 1.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
* Data from square 1 is carried 0 steps, since it's at the access port.
|
||||||
|
* Data from square 12 is carried 3 steps, such as: down, left, left.
|
||||||
|
* Data from square 23 is carried only 2 steps: up twice.
|
||||||
|
* Data from square 1024 must be carried 31 steps.
|
||||||
|
|
||||||
|
How many steps are required to carry the data from the square identified in your puzzle input all the way to the access port?
|
||||||
|
|
||||||
|
### Analysis
|
||||||
|
|
||||||
|
I freely admit that I worked out the program I wanted to write using graph paper and some Python doodles. There's no point in trying to write a Joy program until I'm sure I understand the problem well enough.
|
||||||
|
|
||||||
|
The first thing I did was to write a column of numbers from 1 to n (32 as it happens) and next to them the desired output number, to look for patterns directly:
|
||||||
|
|
||||||
|
1 0
|
||||||
|
2 1
|
||||||
|
3 2
|
||||||
|
4 1
|
||||||
|
5 2
|
||||||
|
6 1
|
||||||
|
7 2
|
||||||
|
8 1
|
||||||
|
9 2
|
||||||
|
10 3
|
||||||
|
11 2
|
||||||
|
12 3
|
||||||
|
13 4
|
||||||
|
14 3
|
||||||
|
15 2
|
||||||
|
16 3
|
||||||
|
17 4
|
||||||
|
18 3
|
||||||
|
19 2
|
||||||
|
20 3
|
||||||
|
21 4
|
||||||
|
22 3
|
||||||
|
23 2
|
||||||
|
24 3
|
||||||
|
25 4
|
||||||
|
26 5
|
||||||
|
27 4
|
||||||
|
28 3
|
||||||
|
29 4
|
||||||
|
30 5
|
||||||
|
31 6
|
||||||
|
32 5
|
||||||
|
|
||||||
|
There are four groups repeating for a given "rank", then the pattern enlarges and four groups repeat again, etc.
|
||||||
|
|
||||||
|
1 2
|
||||||
|
3 2 3 4
|
||||||
|
5 4 3 4 5 6
|
||||||
|
7 6 5 4 5 6 7 8
|
||||||
|
9 8 7 6 5 6 7 8 9 10
|
||||||
|
|
||||||
|
Four of this pyramid interlock to tile the plane extending from the initial "1" square.
|
||||||
|
|
||||||
|
|
||||||
|
2 3 | 4 5 | 6 7 | 8 9
|
||||||
|
10 11 12 13|14 15 16 17|18 19 20 21|22 23 24 25
|
||||||
|
|
||||||
|
And so on.
|
||||||
|
|
||||||
|
We can figure out the pattern for a row of the pyramid at a given "rank" $k$:
|
||||||
|
|
||||||
|
$2k - 1, 2k - 2, ..., k, k + 1, k + 2, ..., 2k$
|
||||||
|
|
||||||
|
or
|
||||||
|
|
||||||
|
$k + (k - 1), k + (k - 2), ..., k, k + 1, k + 2, ..., k + k$
|
||||||
|
|
||||||
|
This shows that the series consists at each place of $k$ plus some number that begins at $k - 1$, decreases to zero, then increases to $k$. Each row has $2k$ members.
|
||||||
|
|
||||||
|
Let's figure out how, given an index into a row, we can calculate the value there. The index will be from 0 to $k - 1$.
|
||||||
|
|
||||||
|
Let's look at an example, with $k = 4$:
|
||||||
|
|
||||||
|
0 1 2 3 4 5 6 7
|
||||||
|
7 6 5 4 5 6 7 8
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
k = 4
|
||||||
|
```
|
||||||
|
|
||||||
|
Subtract $k$ from the index and take the absolute value:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
for n in range(2 * k):
|
||||||
|
print abs(n - k),
|
||||||
|
```
|
||||||
|
|
||||||
|
4 3 2 1 0 1 2 3
|
||||||
|
|
||||||
|
|
||||||
|
Not quite. Subtract $k - 1$ from the index and take the absolute value:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
for n in range(2 * k):
|
||||||
|
print abs(n - (k - 1)),
|
||||||
|
```
|
||||||
|
|
||||||
|
3 2 1 0 1 2 3 4
|
||||||
|
|
||||||
|
|
||||||
|
Great, now add $k$...
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
for n in range(2 * k):
|
||||||
|
print abs(n - (k - 1)) + k,
|
||||||
|
```
|
||||||
|
|
||||||
|
7 6 5 4 5 6 7 8
|
||||||
|
|
||||||
|
|
||||||
|
So to write a function that can give us the value of a row at a given index:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
def row_value(k, i):
|
||||||
|
i %= (2 * k) # wrap the index at the row boundary.
|
||||||
|
return abs(i - (k - 1)) + k
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
k = 5
|
||||||
|
for i in range(2 * k):
|
||||||
|
print row_value(k, i),
|
||||||
|
```
|
||||||
|
|
||||||
|
9 8 7 6 5 6 7 8 9 10
|
||||||
|
|
||||||
|
|
||||||
|
(I'm leaving out details of how I figured this all out and just giving the relevent bits. It took a little while to zero in of the aspects of the pattern that were important for the task.)
|
||||||
|
|
||||||
|
### Finding the rank and offset of a number.
|
||||||
|
Now that we can compute the desired output value for a given rank and the offset (index) into that rank, we need to determine how to find the rank and offset of a number.
|
||||||
|
|
||||||
|
The rank is easy to find by iteratively stripping off the amount already covered by previous ranks until you find the one that brackets the target number. Because each row is $2k$ places and there are $4$ per rank each rank contains $8k$ places. Counting the initial square we have:
|
||||||
|
|
||||||
|
$corner_k = 1 + \sum_{n=1}^k 8n$
|
||||||
|
|
||||||
|
I'm not mathematically sophisticated enough to turn this directly into a formula (but Sympy is, see below.) I'm going to write a simple Python function to iterate and search:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
def rank_and_offset(n):
|
||||||
|
assert n >= 2 # Guard the domain.
|
||||||
|
n -= 2 # Subtract two,
|
||||||
|
# one for the initial square,
|
||||||
|
# and one because we are counting from 1 instead of 0.
|
||||||
|
k = 1
|
||||||
|
while True:
|
||||||
|
m = 8 * k # The number of places total in this rank, 4(2k).
|
||||||
|
if n < m:
|
||||||
|
return k, n % (2 * k)
|
||||||
|
n -= m # Remove this rank's worth.
|
||||||
|
k += 1
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
for n in range(2, 51):
|
||||||
|
print n, rank_and_offset(n)
|
||||||
|
```
|
||||||
|
|
||||||
|
2 (1, 0)
|
||||||
|
3 (1, 1)
|
||||||
|
4 (1, 0)
|
||||||
|
5 (1, 1)
|
||||||
|
6 (1, 0)
|
||||||
|
7 (1, 1)
|
||||||
|
8 (1, 0)
|
||||||
|
9 (1, 1)
|
||||||
|
10 (2, 0)
|
||||||
|
11 (2, 1)
|
||||||
|
12 (2, 2)
|
||||||
|
13 (2, 3)
|
||||||
|
14 (2, 0)
|
||||||
|
15 (2, 1)
|
||||||
|
16 (2, 2)
|
||||||
|
17 (2, 3)
|
||||||
|
18 (2, 0)
|
||||||
|
19 (2, 1)
|
||||||
|
20 (2, 2)
|
||||||
|
21 (2, 3)
|
||||||
|
22 (2, 0)
|
||||||
|
23 (2, 1)
|
||||||
|
24 (2, 2)
|
||||||
|
25 (2, 3)
|
||||||
|
26 (3, 0)
|
||||||
|
27 (3, 1)
|
||||||
|
28 (3, 2)
|
||||||
|
29 (3, 3)
|
||||||
|
30 (3, 4)
|
||||||
|
31 (3, 5)
|
||||||
|
32 (3, 0)
|
||||||
|
33 (3, 1)
|
||||||
|
34 (3, 2)
|
||||||
|
35 (3, 3)
|
||||||
|
36 (3, 4)
|
||||||
|
37 (3, 5)
|
||||||
|
38 (3, 0)
|
||||||
|
39 (3, 1)
|
||||||
|
40 (3, 2)
|
||||||
|
41 (3, 3)
|
||||||
|
42 (3, 4)
|
||||||
|
43 (3, 5)
|
||||||
|
44 (3, 0)
|
||||||
|
45 (3, 1)
|
||||||
|
46 (3, 2)
|
||||||
|
47 (3, 3)
|
||||||
|
48 (3, 4)
|
||||||
|
49 (3, 5)
|
||||||
|
50 (4, 0)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
for n in range(2, 51):
|
||||||
|
k, i = rank_and_offset(n)
|
||||||
|
print n, row_value(k, i)
|
||||||
|
```
|
||||||
|
|
||||||
|
2 1
|
||||||
|
3 2
|
||||||
|
4 1
|
||||||
|
5 2
|
||||||
|
6 1
|
||||||
|
7 2
|
||||||
|
8 1
|
||||||
|
9 2
|
||||||
|
10 3
|
||||||
|
11 2
|
||||||
|
12 3
|
||||||
|
13 4
|
||||||
|
14 3
|
||||||
|
15 2
|
||||||
|
16 3
|
||||||
|
17 4
|
||||||
|
18 3
|
||||||
|
19 2
|
||||||
|
20 3
|
||||||
|
21 4
|
||||||
|
22 3
|
||||||
|
23 2
|
||||||
|
24 3
|
||||||
|
25 4
|
||||||
|
26 5
|
||||||
|
27 4
|
||||||
|
28 3
|
||||||
|
29 4
|
||||||
|
30 5
|
||||||
|
31 6
|
||||||
|
32 5
|
||||||
|
33 4
|
||||||
|
34 3
|
||||||
|
35 4
|
||||||
|
36 5
|
||||||
|
37 6
|
||||||
|
38 5
|
||||||
|
39 4
|
||||||
|
40 3
|
||||||
|
41 4
|
||||||
|
42 5
|
||||||
|
43 6
|
||||||
|
44 5
|
||||||
|
45 4
|
||||||
|
46 3
|
||||||
|
47 4
|
||||||
|
48 5
|
||||||
|
49 6
|
||||||
|
50 7
|
||||||
|
|
||||||
|
|
||||||
|
### Putting it all together
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
def row_value(k, i):
|
||||||
|
return abs(i - (k - 1)) + k
|
||||||
|
|
||||||
|
|
||||||
|
def rank_and_offset(n):
|
||||||
|
n -= 2 # Subtract two,
|
||||||
|
# one for the initial square,
|
||||||
|
# and one because we are counting from 1 instead of 0.
|
||||||
|
k = 1
|
||||||
|
while True:
|
||||||
|
m = 8 * k # The number of places total in this rank, 4(2k).
|
||||||
|
if n < m:
|
||||||
|
return k, n % (2 * k)
|
||||||
|
n -= m # Remove this rank's worth.
|
||||||
|
k += 1
|
||||||
|
|
||||||
|
|
||||||
|
def aoc20173(n):
|
||||||
|
if n <= 1:
|
||||||
|
return 0
|
||||||
|
k, i = rank_and_offset(n)
|
||||||
|
return row_value(k, i)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
aoc20173(23)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
2
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
aoc20173(23000)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
105
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
aoc20173(23000000000000)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
4572225
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Sympy to the Rescue
|
||||||
|
### Find the rank for large numbers
|
||||||
|
Using e.g. Sympy we can find the rank directly by solving for the roots of an equation. For large numbers this will (eventually) be faster than iterating as `rank_and_offset()` does.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from sympy import floor, lambdify, solve, symbols
|
||||||
|
from sympy import init_printing
|
||||||
|
init_printing()
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
k = symbols('k')
|
||||||
|
```
|
||||||
|
|
||||||
|
Since
|
||||||
|
|
||||||
|
$1 + 2 + 3 + ... + N = \frac{N(N + 1)}{2}$
|
||||||
|
|
||||||
|
and
|
||||||
|
|
||||||
|
$\sum_{n=1}^k 8n = 8(\sum_{n=1}^k n) = 8\frac{k(k + 1)}{2}$
|
||||||
|
|
||||||
|
We want:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
E = 2 + 8 * k * (k + 1) / 2 # For the reason for adding 2 see above.
|
||||||
|
|
||||||
|
E
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$4 k \left(k + 1\right) + 2$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
We can write a function to solve for $k$ given some $n$...
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
def rank_of(n):
|
||||||
|
return floor(max(solve(E - n, k))) + 1
|
||||||
|
```
|
||||||
|
|
||||||
|
First `solve()` for $E - n = 0$ which has two solutions (because the equation is quadratic so it has two roots) and since we only care about the larger one we use `max()` to select it. It will generally not be a nice integer (unless $n$ is the number of an end-corner of a rank) so we take the `floor()` and add 1 to get the integer rank of $n$. (Taking the `ceiling()` gives off-by-one errors on the rank boundaries. I don't know why. I'm basically like a monkey doing math here.) =-D
|
||||||
|
|
||||||
|
It gives correct answers:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
for n in (9, 10, 25, 26, 49, 50):
|
||||||
|
print n, rank_of(n)
|
||||||
|
```
|
||||||
|
|
||||||
|
9 1
|
||||||
|
10 2
|
||||||
|
25 2
|
||||||
|
26 3
|
||||||
|
49 3
|
||||||
|
50 4
|
||||||
|
|
||||||
|
|
||||||
|
And it runs much faster (at least for large numbers):
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
%time rank_of(23000000000000) # Compare runtime with rank_and_offset()!
|
||||||
|
```
|
||||||
|
|
||||||
|
CPU times: user 68 ms, sys: 8 ms, total: 76 ms
|
||||||
|
Wall time: 73.8 ms
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$2397916$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
%time rank_and_offset(23000000000000)
|
||||||
|
```
|
||||||
|
|
||||||
|
CPU times: user 308 ms, sys: 0 ns, total: 308 ms
|
||||||
|
Wall time: 306 ms
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$\left ( 2397916, \quad 223606\right )$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
After finding the rank you would still have to find the actual value of the rank's first corner and subtract it (plus 2) from the number and compute the offset as above and then the final output, but this overhead is partially shared by the other method, and overshadowed by the time it (the other iterative method) would take for really big inputs.
|
||||||
|
|
||||||
|
The fun thing to do here would be to graph the actual runtime of both methods against each other to find the trade-off point.
|
||||||
|
|
||||||
|
### It took me a second to realize I could do this...
|
||||||
|
Sympy is a *symbolic* math library, and it supports symbolic manipulation of equations. I can put in $y$ (instead of a value) and ask it to solve for $k$.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
y = symbols('y')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
g, f = solve(E - y, k)
|
||||||
|
```
|
||||||
|
|
||||||
|
The equation is quadratic so there are two roots, we are interested in the greater one...
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
g
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$- \frac{1}{2} \sqrt{y - 1} - \frac{1}{2}$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
f
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$\frac{1}{2} \sqrt{y - 1} - \frac{1}{2}$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Now we can take the `floor()`, add 1, and `lambdify()` the equation to get a Python function that calculates the rank directly.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
floor(f) + 1
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$\lfloor{\frac{1}{2} \sqrt{y - 1} - \frac{1}{2}}\rfloor + 1$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
F = lambdify(y, floor(f) + 1)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
for n in (9, 10, 25, 26, 49, 50):
|
||||||
|
print n, int(F(n))
|
||||||
|
```
|
||||||
|
|
||||||
|
9 1
|
||||||
|
10 2
|
||||||
|
25 2
|
||||||
|
26 3
|
||||||
|
49 3
|
||||||
|
50 4
|
||||||
|
|
||||||
|
|
||||||
|
It's pretty fast.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
%time int(F(23000000000000)) # The clear winner.
|
||||||
|
```
|
||||||
|
|
||||||
|
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
|
||||||
|
Wall time: 11.9 µs
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$2397916$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Knowing the equation we could write our own function manually, but the speed is no better.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from math import floor as mfloor, sqrt
|
||||||
|
|
||||||
|
def mrank_of(n):
|
||||||
|
return int(mfloor(sqrt(23000000000000 - 1) / 2 - 0.5) + 1)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
%time mrank_of(23000000000000)
|
||||||
|
```
|
||||||
|
|
||||||
|
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
|
||||||
|
Wall time: 12.9 µs
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$2397916$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### Given $n$ and a rank, compute the offset.
|
||||||
|
|
||||||
|
Now that we have a fast way to get the rank, we still need to use it to compute the offset into a pyramid row.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
def offset_of(n, k):
|
||||||
|
return (n - 2 + 4 * k * (k - 1)) % (2 * k)
|
||||||
|
```
|
||||||
|
|
||||||
|
(Note the sneaky way the sign changes from $k(k + 1)$ to $k(k - 1)$. This is because we want to subract the $(k - 1)$th rank's total places (its own and those of lesser rank) from our $n$ of rank $k$. Substituting $k - 1$ for $k$ in $k(k + 1)$ gives $(k - 1)(k - 1 + 1)$, which of course simplifies to $k(k - 1)$.)
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
offset_of(23000000000000, 2397916)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$223606$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
So, we can compute the rank, then the offset, then the row value.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
def rank_of(n):
|
||||||
|
return int(mfloor(sqrt(n - 1) / 2 - 0.5) + 1)
|
||||||
|
|
||||||
|
|
||||||
|
def offset_of(n, k):
|
||||||
|
return (n - 2 + 4 * k * (k - 1)) % (2 * k)
|
||||||
|
|
||||||
|
|
||||||
|
def row_value(k, i):
|
||||||
|
return abs(i - (k - 1)) + k
|
||||||
|
|
||||||
|
|
||||||
|
def aoc20173(n):
|
||||||
|
k = rank_of(n)
|
||||||
|
i = offset_of(n, k)
|
||||||
|
return row_value(k, i)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
aoc20173(23)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$2$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
aoc20173(23000)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$105$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
aoc20173(23000000000000)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$4572225$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
%time aoc20173(23000000000000000000000000) # Fast for large values.
|
||||||
|
```
|
||||||
|
|
||||||
|
CPU times: user 0 ns, sys: 0 ns, total: 0 ns
|
||||||
|
Wall time: 20 µs
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
$$2690062495969$$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# A Joy Version
|
||||||
|
At this point I feel confident that I can implement a concise version of this code in Joy. ;-)
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from notebook_preamble import J, V, define
|
||||||
|
```
|
||||||
|
|
||||||
|
### `rank_of`
|
||||||
|
|
||||||
|
n rank_of
|
||||||
|
---------------
|
||||||
|
k
|
||||||
|
|
||||||
|
The translation is straightforward.
|
||||||
|
|
||||||
|
int(floor(sqrt(n - 1) / 2 - 0.5) + 1)
|
||||||
|
|
||||||
|
rank_of == -- sqrt 2 / 0.5 - floor ++
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('rank_of == -- sqrt 2 / 0.5 - floor ++')
|
||||||
|
```
|
||||||
|
|
||||||
|
### `offset_of`
|
||||||
|
|
||||||
|
n k offset_of
|
||||||
|
-------------------
|
||||||
|
i
|
||||||
|
|
||||||
|
(n - 2 + 4 * k * (k - 1)) % (2 * k)
|
||||||
|
|
||||||
|
A little tricky...
|
||||||
|
|
||||||
|
n k dup 2 *
|
||||||
|
n k k 2 *
|
||||||
|
n k k*2 [Q] dip %
|
||||||
|
n k Q k*2 %
|
||||||
|
|
||||||
|
n k dup --
|
||||||
|
n k k --
|
||||||
|
n k k-1 4 * * 2 + -
|
||||||
|
n k*k-1*4 2 + -
|
||||||
|
n k*k-1*4+2 -
|
||||||
|
n-k*k-1*4+2
|
||||||
|
|
||||||
|
n-k*k-1*4+2 k*2 %
|
||||||
|
n-k*k-1*4+2%k*2
|
||||||
|
|
||||||
|
Ergo:
|
||||||
|
|
||||||
|
offset_of == dup 2 * [dup -- 4 * * 2 + -] dip %
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('offset_of == dup 2 * [dup -- 4 * * 2 + -] dip %')
|
||||||
|
```
|
||||||
|
|
||||||
|
### `row_value`
|
||||||
|
|
||||||
|
k i row_value
|
||||||
|
-------------------
|
||||||
|
n
|
||||||
|
|
||||||
|
abs(i - (k - 1)) + k
|
||||||
|
|
||||||
|
k i over -- - abs +
|
||||||
|
k i k -- - abs +
|
||||||
|
k i k-1 - abs +
|
||||||
|
k i-k-1 abs +
|
||||||
|
k |i-k-1| +
|
||||||
|
k+|i-k-1|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('row_value == over -- - abs +')
|
||||||
|
```
|
||||||
|
|
||||||
|
### `aoc2017.3`
|
||||||
|
|
||||||
|
n aoc2017.3
|
||||||
|
-----------------
|
||||||
|
m
|
||||||
|
|
||||||
|
n dup rank_of
|
||||||
|
n k [offset_of] dupdip
|
||||||
|
n k offset_of k
|
||||||
|
i k swap row_value
|
||||||
|
k i row_value
|
||||||
|
m
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('aoc2017.3 == dup rank_of [offset_of] dupdip swap row_value')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('23 aoc2017.3')
|
||||||
|
```
|
||||||
|
|
||||||
|
2
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('23000 aoc2017.3')
|
||||||
|
```
|
||||||
|
|
||||||
|
105
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('23000000000000 aoc2017.3')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 23000000000000 aoc2017.3
|
||||||
|
23000000000000 . aoc2017.3
|
||||||
|
23000000000000 . dup rank_of [offset_of] dupdip swap row_value
|
||||||
|
23000000000000 23000000000000 . rank_of [offset_of] dupdip swap row_value
|
||||||
|
23000000000000 23000000000000 . -- sqrt 2 / 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||||
|
23000000000000 22999999999999 . sqrt 2 / 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||||
|
23000000000000 4795831.523312615 . 2 / 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||||
|
23000000000000 4795831.523312615 2 . / 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||||
|
23000000000000 2397915.7616563076 . 0.5 - floor ++ [offset_of] dupdip swap row_value
|
||||||
|
23000000000000 2397915.7616563076 0.5 . - floor ++ [offset_of] dupdip swap row_value
|
||||||
|
23000000000000 2397915.2616563076 . floor ++ [offset_of] dupdip swap row_value
|
||||||
|
23000000000000 2397915 . ++ [offset_of] dupdip swap row_value
|
||||||
|
23000000000000 2397916 . [offset_of] dupdip swap row_value
|
||||||
|
23000000000000 2397916 [offset_of] . dupdip swap row_value
|
||||||
|
23000000000000 2397916 . offset_of 2397916 swap row_value
|
||||||
|
23000000000000 2397916 . dup 2 * [dup -- 4 * * 2 + -] dip % 2397916 swap row_value
|
||||||
|
23000000000000 2397916 2397916 . 2 * [dup -- 4 * * 2 + -] dip % 2397916 swap row_value
|
||||||
|
23000000000000 2397916 2397916 2 . * [dup -- 4 * * 2 + -] dip % 2397916 swap row_value
|
||||||
|
23000000000000 2397916 4795832 . [dup -- 4 * * 2 + -] dip % 2397916 swap row_value
|
||||||
|
23000000000000 2397916 4795832 [dup -- 4 * * 2 + -] . dip % 2397916 swap row_value
|
||||||
|
23000000000000 2397916 . dup -- 4 * * 2 + - 4795832 % 2397916 swap row_value
|
||||||
|
23000000000000 2397916 2397916 . -- 4 * * 2 + - 4795832 % 2397916 swap row_value
|
||||||
|
23000000000000 2397916 2397915 . 4 * * 2 + - 4795832 % 2397916 swap row_value
|
||||||
|
23000000000000 2397916 2397915 4 . * * 2 + - 4795832 % 2397916 swap row_value
|
||||||
|
23000000000000 2397916 9591660 . * 2 + - 4795832 % 2397916 swap row_value
|
||||||
|
23000000000000 22999994980560 . 2 + - 4795832 % 2397916 swap row_value
|
||||||
|
23000000000000 22999994980560 2 . + - 4795832 % 2397916 swap row_value
|
||||||
|
23000000000000 22999994980562 . - 4795832 % 2397916 swap row_value
|
||||||
|
5019438 . 4795832 % 2397916 swap row_value
|
||||||
|
5019438 4795832 . % 2397916 swap row_value
|
||||||
|
223606 . 2397916 swap row_value
|
||||||
|
223606 2397916 . swap row_value
|
||||||
|
2397916 223606 . row_value
|
||||||
|
2397916 223606 . over -- - abs +
|
||||||
|
2397916 223606 2397916 . -- - abs +
|
||||||
|
2397916 223606 2397915 . - abs +
|
||||||
|
2397916 -2174309 . abs +
|
||||||
|
2397916 2174309 . +
|
||||||
|
4572225 .
|
||||||
|
|
||||||
|
|
||||||
|
rank_of == -- sqrt 2 / 0.5 - floor ++
|
||||||
|
offset_of == dup 2 * [dup -- 4 * * 2 + -] dip %
|
||||||
|
row_value == over -- - abs +
|
||||||
|
|
||||||
|
aoc2017.3 == dup rank_of [offset_of] dupdip swap row_value
|
||||||
|
After Width: | Height: | Size: 677 B |
|
After Width: | Height: | Size: 566 B |
|
After Width: | Height: | Size: 977 B |
|
After Width: | Height: | Size: 655 B |
|
After Width: | Height: | Size: 665 B |
|
After Width: | Height: | Size: 758 B |
|
After Width: | Height: | Size: 566 B |
|
After Width: | Height: | Size: 566 B |
|
After Width: | Height: | Size: 453 B |
|
After Width: | Height: | Size: 239 B |
|
After Width: | Height: | Size: 337 B |
|
After Width: | Height: | Size: 447 B |
|
After Width: | Height: | Size: 784 B |
|
|
@ -0,0 +1,139 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Advent of Code 2017\n",
|
||||||
|
"\n",
|
||||||
|
"## December 4th\n",
|
||||||
|
"To ensure security, a valid passphrase must contain no duplicate words.\n",
|
||||||
|
"\n",
|
||||||
|
"For example:\n",
|
||||||
|
"\n",
|
||||||
|
"* aa bb cc dd ee is valid.\n",
|
||||||
|
"* aa bb cc dd aa is not valid - the word aa appears more than once.\n",
|
||||||
|
"* aa bb cc dd aaa is valid - aa and aaa count as different words.\n",
|
||||||
|
"\n",
|
||||||
|
"The system's full passphrase list is available as your puzzle input. How many passphrases are valid?"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from notebook_preamble import J, V, define"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"I'll assume the input is a Joy sequence of sequences of integers.\n",
|
||||||
|
"\n",
|
||||||
|
" [[5 1 9 5]\n",
|
||||||
|
" [7 5 4 3]\n",
|
||||||
|
" [2 4 6 8]]\n",
|
||||||
|
"\n",
|
||||||
|
"So, obviously, the initial form will be a `step` function:\n",
|
||||||
|
"\n",
|
||||||
|
" AoC2017.4 == 0 swap [F +] step"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"\n",
|
||||||
|
" F == [size] [unique size] cleave =\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The `step_zero` combinator includes the `0 swap` that would normally open one of these definitions:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"0 roll> step\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[step_zero] help')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
" AoC2017.4 == [F +] step_zero"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('AoC2017.4 == [[size] [unique size] cleave = +] step_zero')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"2\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('''\n",
|
||||||
|
"\n",
|
||||||
|
"[[5 1 9 5]\n",
|
||||||
|
" [7 5 4 3]\n",
|
||||||
|
" [2 4 6 8]] AoC2017.4\n",
|
||||||
|
"\n",
|
||||||
|
"''')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 2",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python2"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 2
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython2",
|
||||||
|
"version": "2.7.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,64 @@
|
||||||
|
|
||||||
|
# Advent of Code 2017
|
||||||
|
|
||||||
|
## December 4th
|
||||||
|
To ensure security, a valid passphrase must contain no duplicate words.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
* aa bb cc dd ee is valid.
|
||||||
|
* aa bb cc dd aa is not valid - the word aa appears more than once.
|
||||||
|
* aa bb cc dd aaa is valid - aa and aaa count as different words.
|
||||||
|
|
||||||
|
The system's full passphrase list is available as your puzzle input. How many passphrases are valid?
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from notebook_preamble import J, V, define
|
||||||
|
```
|
||||||
|
|
||||||
|
I'll assume the input is a Joy sequence of sequences of integers.
|
||||||
|
|
||||||
|
[[5 1 9 5]
|
||||||
|
[7 5 4 3]
|
||||||
|
[2 4 6 8]]
|
||||||
|
|
||||||
|
So, obviously, the initial form will be a `step` function:
|
||||||
|
|
||||||
|
AoC2017.4 == 0 swap [F +] step
|
||||||
|
|
||||||
|
|
||||||
|
F == [size] [unique size] cleave =
|
||||||
|
|
||||||
|
|
||||||
|
The `step_zero` combinator includes the `0 swap` that would normally open one of these definitions:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[step_zero] help')
|
||||||
|
```
|
||||||
|
|
||||||
|
0 roll> step
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
AoC2017.4 == [F +] step_zero
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('AoC2017.4 == [[size] [unique size] cleave = +] step_zero')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('''
|
||||||
|
|
||||||
|
[[5 1 9 5]
|
||||||
|
[7 5 4 3]
|
||||||
|
[2 4 6 8]] AoC2017.4
|
||||||
|
|
||||||
|
''')
|
||||||
|
```
|
||||||
|
|
||||||
|
2
|
||||||
|
|
||||||
|
|
@ -0,0 +1,380 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Advent of Code 2017\n",
|
||||||
|
"\n",
|
||||||
|
"## December 5th\n",
|
||||||
|
"...a list of the offsets for each jump. Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one. Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list.\n",
|
||||||
|
"\n",
|
||||||
|
"In addition, these instructions are a little strange; after each jump, the offset of that instruction increases by 1. So, if you come across an offset of 3, you would move three instructions forward, but change it to a 4 for the next time it is encountered.\n",
|
||||||
|
"\n",
|
||||||
|
"For example, consider the following list of jump offsets:\n",
|
||||||
|
"\n",
|
||||||
|
" 0\n",
|
||||||
|
" 3\n",
|
||||||
|
" 0\n",
|
||||||
|
" 1\n",
|
||||||
|
" -3\n",
|
||||||
|
"\n",
|
||||||
|
"Positive jumps (\"forward\") move downward; negative jumps move upward. For legibility in this example, these offset values will be written all on one line, with the current instruction marked in parentheses. The following steps would be taken before an exit is found:\n",
|
||||||
|
"\n",
|
||||||
|
"* (0) 3 0 1 -3 - before we have taken any steps.\n",
|
||||||
|
"* (1) 3 0 1 -3 - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1.\n",
|
||||||
|
"* 2 (3) 0 1 -3 - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2.\n",
|
||||||
|
"* 2 4 0 1 (-3) - jump all the way to the end; leave a 4 behind.\n",
|
||||||
|
"* 2 (4) 0 1 -2 - go back to where we just were; increment -3 to -2.\n",
|
||||||
|
"* 2 5 0 1 -2 - jump 4 steps forward, escaping the maze.\n",
|
||||||
|
"\n",
|
||||||
|
"In this example, the exit is reached in 5 steps.\n",
|
||||||
|
"\n",
|
||||||
|
"How many steps does it take to reach the exit?"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Breakdown\n",
|
||||||
|
"For now, I'm going to assume a starting state with the size of the sequence pre-computed. We need it to define the exit condition and it is a trivial preamble to generate it. We then need and `index` and a `step-count`, which are both initially zero. Then we have the sequence itself, and some recursive function `F` that does the work.\n",
|
||||||
|
"\n",
|
||||||
|
" size index step-count [...] F\n",
|
||||||
|
" -----------------------------------\n",
|
||||||
|
" step-count\n",
|
||||||
|
"\n",
|
||||||
|
" F == [P] [T] [R1] [R2] genrec\n",
|
||||||
|
"\n",
|
||||||
|
"Later on I was thinking about it and the Forth heuristic came to mind, to wit: four things on the stack are kind of much. Immediately I realized that the size properly belongs in the predicate of `F`! D'oh!\n",
|
||||||
|
"\n",
|
||||||
|
" index step-count [...] F\n",
|
||||||
|
" ------------------------------\n",
|
||||||
|
" step-count"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"So, let's start by nailing down the predicate:\n",
|
||||||
|
"\n",
|
||||||
|
" F == [P] [T] [R1] [R2] genrec\n",
|
||||||
|
" == [P] [T] [R1 [F] R2] ifte\n",
|
||||||
|
"\n",
|
||||||
|
" 0 0 [0 3 0 1 -3] popop 5 >=\n",
|
||||||
|
"\n",
|
||||||
|
" P == popop 5 >="
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now we need the else-part:\n",
|
||||||
|
"\n",
|
||||||
|
" index step-count [0 3 0 1 -3] roll< popop\n",
|
||||||
|
"\n",
|
||||||
|
" E == roll< popop"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Last but not least, the recursive branch\n",
|
||||||
|
"\n",
|
||||||
|
" 0 0 [0 3 0 1 -3] R1 [F] R2\n",
|
||||||
|
"\n",
|
||||||
|
"The `R1` function has a big job:\n",
|
||||||
|
"\n",
|
||||||
|
" R1 == get the value at index\n",
|
||||||
|
" increment the value at the index\n",
|
||||||
|
" add the value gotten to the index\n",
|
||||||
|
" increment the step count\n",
|
||||||
|
"\n",
|
||||||
|
"The only tricky thing there is incrementing an integer in the sequence. Joy sequences are not particularly good for random access. We could encode the list of jump offsets in a big integer and use math to do the processing for a good speed-up, but it still wouldn't beat the performance of e.g. a mutable array. This is just one of those places where \"plain vanilla\" Joypy doesn't shine (in default performance. The legendary *Sufficiently-Smart Compiler* would of course rewrite this function to use an array \"under the hood\".)\n",
|
||||||
|
"\n",
|
||||||
|
"In the meantime, I'm going to write a primitive function that just does what we need."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from notebook_preamble import D, J, V, define\n",
|
||||||
|
"from joy.library import SimpleFunctionWrapper\n",
|
||||||
|
"from joy.utils.stack import list_to_stack\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"@SimpleFunctionWrapper\n",
|
||||||
|
"def incr_at(stack):\n",
|
||||||
|
" '''Given a index and a sequence of integers, increment the integer at the index.\n",
|
||||||
|
"\n",
|
||||||
|
" E.g.:\n",
|
||||||
|
"\n",
|
||||||
|
" 3 [0 1 2 3 4 5] incr_at\n",
|
||||||
|
" -----------------------------\n",
|
||||||
|
" [0 1 2 4 4 5]\n",
|
||||||
|
" \n",
|
||||||
|
" '''\n",
|
||||||
|
" sequence, (i, stack) = stack\n",
|
||||||
|
" mem = []\n",
|
||||||
|
" while i >= 0:\n",
|
||||||
|
" term, sequence = sequence\n",
|
||||||
|
" mem.append(term)\n",
|
||||||
|
" i -= 1\n",
|
||||||
|
" mem[-1] += 1\n",
|
||||||
|
" return list_to_stack(mem, sequence), stack\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"D['incr_at'] = incr_at"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[0 1 2 4 4 5]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('3 [0 1 2 3 4 5] incr_at')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### get the value at index\n",
|
||||||
|
"\n",
|
||||||
|
" 3 0 [0 1 2 3 4] [roll< at] nullary\n",
|
||||||
|
" 3 0 [0 1 2 n 4] n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### increment the value at the index\n",
|
||||||
|
"\n",
|
||||||
|
" 3 0 [0 1 2 n 4] n [Q] dip\n",
|
||||||
|
" 3 0 [0 1 2 n 4] Q n\n",
|
||||||
|
" 3 0 [0 1 2 n 4] [popd incr_at] unary n\n",
|
||||||
|
" 3 0 [0 1 2 n+1 4] n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### add the value gotten to the index\n",
|
||||||
|
"\n",
|
||||||
|
" 3 0 [0 1 2 n+1 4] n [+] cons dipd\n",
|
||||||
|
" 3 0 [0 1 2 n+1 4] [n +] dipd\n",
|
||||||
|
" 3 n + 0 [0 1 2 n+1 4]\n",
|
||||||
|
" 3+n 0 [0 1 2 n+1 4]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### increment the step count\n",
|
||||||
|
"\n",
|
||||||
|
" 3+n 0 [0 1 2 n+1 4] [++] dip\n",
|
||||||
|
" 3+n 1 [0 1 2 n+1 4]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### All together now...\n",
|
||||||
|
"\n",
|
||||||
|
" get_value == [roll< at] nullary\n",
|
||||||
|
" incr_value == [[popd incr_at] unary] dip\n",
|
||||||
|
" add_value == [+] cons dipd\n",
|
||||||
|
" incr_step_count == [++] dip\n",
|
||||||
|
"\n",
|
||||||
|
" R1 == get_value incr_value add_value incr_step_count\n",
|
||||||
|
"\n",
|
||||||
|
" F == [P] [T] [R1] primrec\n",
|
||||||
|
" \n",
|
||||||
|
" F == [popop !size! >=] [roll< pop] [get_value incr_value add_value incr_step_count] primrec"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from joy.library import DefinitionWrapper\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"DefinitionWrapper.add_definitions('''\n",
|
||||||
|
"\n",
|
||||||
|
" get_value == [roll< at] nullary\n",
|
||||||
|
" incr_value == [[popd incr_at] unary] dip\n",
|
||||||
|
" add_value == [+] cons dipd\n",
|
||||||
|
"incr_step_count == [++] dip\n",
|
||||||
|
"\n",
|
||||||
|
" AoC2017.5.0 == get_value incr_value add_value incr_step_count\n",
|
||||||
|
"\n",
|
||||||
|
"''', D)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('F == [popop 5 >=] [roll< popop] [AoC2017.5.0] primrec')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": true
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"5\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('0 0 [0 3 0 1 -3] F')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Preamble for setting up predicate, `index`, and `step-count`\n",
|
||||||
|
"\n",
|
||||||
|
"We want to go from this to this:\n",
|
||||||
|
"\n",
|
||||||
|
" [...] AoC2017.5.preamble\n",
|
||||||
|
" ------------------------------\n",
|
||||||
|
" 0 0 [...] [popop n >=]\n",
|
||||||
|
"\n",
|
||||||
|
"Where `n` is the size of the sequence.\n",
|
||||||
|
"\n",
|
||||||
|
"The first part is obviously `0 0 roll<`, then `dup size`:\n",
|
||||||
|
"\n",
|
||||||
|
" [...] 0 0 roll< dup size\n",
|
||||||
|
" 0 0 [...] n\n",
|
||||||
|
"\n",
|
||||||
|
"Then:\n",
|
||||||
|
"\n",
|
||||||
|
" 0 0 [...] n [>=] cons [popop] swoncat\n",
|
||||||
|
"\n",
|
||||||
|
"So:\n",
|
||||||
|
"\n",
|
||||||
|
" init-index-and-step-count == 0 0 roll<\n",
|
||||||
|
" prepare-predicate == dup size [>=] cons [popop] swoncat\n",
|
||||||
|
"\n",
|
||||||
|
" AoC2017.5.preamble == init-index-and-step-count prepare-predicate"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"DefinitionWrapper.add_definitions('''\n",
|
||||||
|
"\n",
|
||||||
|
"init-index-and-step-count == 0 0 roll<\n",
|
||||||
|
" prepare-predicate == dup size [>=] cons [popop] swoncat\n",
|
||||||
|
"\n",
|
||||||
|
" AoC2017.5.preamble == init-index-and-step-count prepare-predicate\n",
|
||||||
|
"\n",
|
||||||
|
" AoC2017.5 == AoC2017.5.preamble [roll< popop] [AoC2017.5.0] primrec\n",
|
||||||
|
"\n",
|
||||||
|
"''', D)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": false
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"5\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[0 3 0 1 -3] AoC2017.5')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"\n",
|
||||||
|
" AoC2017.5 == AoC2017.5.preamble [roll< popop] [AoC2017.5.0] primrec\n",
|
||||||
|
"\n",
|
||||||
|
" AoC2017.5.0 == get_value incr_value add_value incr_step_count\n",
|
||||||
|
" AoC2017.5.preamble == init-index-and-step-count prepare-predicate\n",
|
||||||
|
"\n",
|
||||||
|
" get_value == [roll< at] nullary\n",
|
||||||
|
" incr_value == [[popd incr_at] unary] dip\n",
|
||||||
|
" add_value == [+] cons dipd\n",
|
||||||
|
" incr_step_count == [++] dip\n",
|
||||||
|
"\n",
|
||||||
|
" init-index-and-step-count == 0 0 roll<\n",
|
||||||
|
" prepare-predicate == dup size [>=] cons [popop] swoncat\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This is by far the largest program I have yet written in Joy. Even with the `incr_at` function it is still a bear. There may be an arrangement of the parameters that would permit more elegant definitions, but it still wouldn't be as efficient as something written in assembly, C, or even Python."
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 2",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python2"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 2
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython2",
|
||||||
|
"version": "2.7.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,244 @@
|
||||||
|
|
||||||
|
# Advent of Code 2017
|
||||||
|
|
||||||
|
## December 5th
|
||||||
|
...a list of the offsets for each jump. Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one. Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list.
|
||||||
|
|
||||||
|
In addition, these instructions are a little strange; after each jump, the offset of that instruction increases by 1. So, if you come across an offset of 3, you would move three instructions forward, but change it to a 4 for the next time it is encountered.
|
||||||
|
|
||||||
|
For example, consider the following list of jump offsets:
|
||||||
|
|
||||||
|
0
|
||||||
|
3
|
||||||
|
0
|
||||||
|
1
|
||||||
|
-3
|
||||||
|
|
||||||
|
Positive jumps ("forward") move downward; negative jumps move upward. For legibility in this example, these offset values will be written all on one line, with the current instruction marked in parentheses. The following steps would be taken before an exit is found:
|
||||||
|
|
||||||
|
* (0) 3 0 1 -3 - before we have taken any steps.
|
||||||
|
* (1) 3 0 1 -3 - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1.
|
||||||
|
* 2 (3) 0 1 -3 - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2.
|
||||||
|
* 2 4 0 1 (-3) - jump all the way to the end; leave a 4 behind.
|
||||||
|
* 2 (4) 0 1 -2 - go back to where we just were; increment -3 to -2.
|
||||||
|
* 2 5 0 1 -2 - jump 4 steps forward, escaping the maze.
|
||||||
|
|
||||||
|
In this example, the exit is reached in 5 steps.
|
||||||
|
|
||||||
|
How many steps does it take to reach the exit?
|
||||||
|
|
||||||
|
## Breakdown
|
||||||
|
For now, I'm going to assume a starting state with the size of the sequence pre-computed. We need it to define the exit condition and it is a trivial preamble to generate it. We then need and `index` and a `step-count`, which are both initially zero. Then we have the sequence itself, and some recursive function `F` that does the work.
|
||||||
|
|
||||||
|
size index step-count [...] F
|
||||||
|
-----------------------------------
|
||||||
|
step-count
|
||||||
|
|
||||||
|
F == [P] [T] [R1] [R2] genrec
|
||||||
|
|
||||||
|
Later on I was thinking about it and the Forth heuristic came to mind, to wit: four things on the stack are kind of much. Immediately I realized that the size properly belongs in the predicate of `F`! D'oh!
|
||||||
|
|
||||||
|
index step-count [...] F
|
||||||
|
------------------------------
|
||||||
|
step-count
|
||||||
|
|
||||||
|
So, let's start by nailing down the predicate:
|
||||||
|
|
||||||
|
F == [P] [T] [R1] [R2] genrec
|
||||||
|
== [P] [T] [R1 [F] R2] ifte
|
||||||
|
|
||||||
|
0 0 [0 3 0 1 -3] popop 5 >=
|
||||||
|
|
||||||
|
P == popop 5 >=
|
||||||
|
|
||||||
|
Now we need the else-part:
|
||||||
|
|
||||||
|
index step-count [0 3 0 1 -3] roll< popop
|
||||||
|
|
||||||
|
E == roll< popop
|
||||||
|
|
||||||
|
Last but not least, the recursive branch
|
||||||
|
|
||||||
|
0 0 [0 3 0 1 -3] R1 [F] R2
|
||||||
|
|
||||||
|
The `R1` function has a big job:
|
||||||
|
|
||||||
|
R1 == get the value at index
|
||||||
|
increment the value at the index
|
||||||
|
add the value gotten to the index
|
||||||
|
increment the step count
|
||||||
|
|
||||||
|
The only tricky thing there is incrementing an integer in the sequence. Joy sequences are not particularly good for random access. We could encode the list of jump offsets in a big integer and use math to do the processing for a good speed-up, but it still wouldn't beat the performance of e.g. a mutable array. This is just one of those places where "plain vanilla" Joypy doesn't shine (in default performance. The legendary *Sufficiently-Smart Compiler* would of course rewrite this function to use an array "under the hood".)
|
||||||
|
|
||||||
|
In the meantime, I'm going to write a primitive function that just does what we need.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from notebook_preamble import D, J, V, define
|
||||||
|
from joy.library import SimpleFunctionWrapper
|
||||||
|
from joy.utils.stack import list_to_stack
|
||||||
|
|
||||||
|
|
||||||
|
@SimpleFunctionWrapper
|
||||||
|
def incr_at(stack):
|
||||||
|
'''Given a index and a sequence of integers, increment the integer at the index.
|
||||||
|
|
||||||
|
E.g.:
|
||||||
|
|
||||||
|
3 [0 1 2 3 4 5] incr_at
|
||||||
|
-----------------------------
|
||||||
|
[0 1 2 4 4 5]
|
||||||
|
|
||||||
|
'''
|
||||||
|
sequence, (i, stack) = stack
|
||||||
|
mem = []
|
||||||
|
while i >= 0:
|
||||||
|
term, sequence = sequence
|
||||||
|
mem.append(term)
|
||||||
|
i -= 1
|
||||||
|
mem[-1] += 1
|
||||||
|
return list_to_stack(mem, sequence), stack
|
||||||
|
|
||||||
|
|
||||||
|
D['incr_at'] = incr_at
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('3 [0 1 2 3 4 5] incr_at')
|
||||||
|
```
|
||||||
|
|
||||||
|
[0 1 2 4 4 5]
|
||||||
|
|
||||||
|
|
||||||
|
### get the value at index
|
||||||
|
|
||||||
|
3 0 [0 1 2 3 4] [roll< at] nullary
|
||||||
|
3 0 [0 1 2 n 4] n
|
||||||
|
|
||||||
|
### increment the value at the index
|
||||||
|
|
||||||
|
3 0 [0 1 2 n 4] n [Q] dip
|
||||||
|
3 0 [0 1 2 n 4] Q n
|
||||||
|
3 0 [0 1 2 n 4] [popd incr_at] unary n
|
||||||
|
3 0 [0 1 2 n+1 4] n
|
||||||
|
|
||||||
|
### add the value gotten to the index
|
||||||
|
|
||||||
|
3 0 [0 1 2 n+1 4] n [+] cons dipd
|
||||||
|
3 0 [0 1 2 n+1 4] [n +] dipd
|
||||||
|
3 n + 0 [0 1 2 n+1 4]
|
||||||
|
3+n 0 [0 1 2 n+1 4]
|
||||||
|
|
||||||
|
### increment the step count
|
||||||
|
|
||||||
|
3+n 0 [0 1 2 n+1 4] [++] dip
|
||||||
|
3+n 1 [0 1 2 n+1 4]
|
||||||
|
|
||||||
|
### All together now...
|
||||||
|
|
||||||
|
get_value == [roll< at] nullary
|
||||||
|
incr_value == [[popd incr_at] unary] dip
|
||||||
|
add_value == [+] cons dipd
|
||||||
|
incr_step_count == [++] dip
|
||||||
|
|
||||||
|
R1 == get_value incr_value add_value incr_step_count
|
||||||
|
|
||||||
|
F == [P] [T] [R1] primrec
|
||||||
|
|
||||||
|
F == [popop !size! >=] [roll< pop] [get_value incr_value add_value incr_step_count] primrec
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from joy.library import DefinitionWrapper
|
||||||
|
|
||||||
|
|
||||||
|
DefinitionWrapper.add_definitions('''
|
||||||
|
|
||||||
|
get_value == [roll< at] nullary
|
||||||
|
incr_value == [[popd incr_at] unary] dip
|
||||||
|
add_value == [+] cons dipd
|
||||||
|
incr_step_count == [++] dip
|
||||||
|
|
||||||
|
AoC2017.5.0 == get_value incr_value add_value incr_step_count
|
||||||
|
|
||||||
|
''', D)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('F == [popop 5 >=] [roll< popop] [AoC2017.5.0] primrec')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('0 0 [0 3 0 1 -3] F')
|
||||||
|
```
|
||||||
|
|
||||||
|
5
|
||||||
|
|
||||||
|
|
||||||
|
### Preamble for setting up predicate, `index`, and `step-count`
|
||||||
|
|
||||||
|
We want to go from this to this:
|
||||||
|
|
||||||
|
[...] AoC2017.5.preamble
|
||||||
|
------------------------------
|
||||||
|
0 0 [...] [popop n >=]
|
||||||
|
|
||||||
|
Where `n` is the size of the sequence.
|
||||||
|
|
||||||
|
The first part is obviously `0 0 roll<`, then `dup size`:
|
||||||
|
|
||||||
|
[...] 0 0 roll< dup size
|
||||||
|
0 0 [...] n
|
||||||
|
|
||||||
|
Then:
|
||||||
|
|
||||||
|
0 0 [...] n [>=] cons [popop] swoncat
|
||||||
|
|
||||||
|
So:
|
||||||
|
|
||||||
|
init-index-and-step-count == 0 0 roll<
|
||||||
|
prepare-predicate == dup size [>=] cons [popop] swoncat
|
||||||
|
|
||||||
|
AoC2017.5.preamble == init-index-and-step-count prepare-predicate
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
DefinitionWrapper.add_definitions('''
|
||||||
|
|
||||||
|
init-index-and-step-count == 0 0 roll<
|
||||||
|
prepare-predicate == dup size [>=] cons [popop] swoncat
|
||||||
|
|
||||||
|
AoC2017.5.preamble == init-index-and-step-count prepare-predicate
|
||||||
|
|
||||||
|
AoC2017.5 == AoC2017.5.preamble [roll< popop] [AoC2017.5.0] primrec
|
||||||
|
|
||||||
|
''', D)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[0 3 0 1 -3] AoC2017.5')
|
||||||
|
```
|
||||||
|
|
||||||
|
5
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
AoC2017.5 == AoC2017.5.preamble [roll< popop] [AoC2017.5.0] primrec
|
||||||
|
|
||||||
|
AoC2017.5.0 == get_value incr_value add_value incr_step_count
|
||||||
|
AoC2017.5.preamble == init-index-and-step-count prepare-predicate
|
||||||
|
|
||||||
|
get_value == [roll< at] nullary
|
||||||
|
incr_value == [[popd incr_at] unary] dip
|
||||||
|
add_value == [+] cons dipd
|
||||||
|
incr_step_count == [++] dip
|
||||||
|
|
||||||
|
init-index-and-step-count == 0 0 roll<
|
||||||
|
prepare-predicate == dup size [>=] cons [popop] swoncat
|
||||||
|
|
||||||
|
|
||||||
|
This is by far the largest program I have yet written in Joy. Even with the `incr_at` function it is still a bear. There may be an arrangement of the parameters that would permit more elegant definitions, but it still wouldn't be as efficient as something written in assembly, C, or even Python.
|
||||||
|
|
@ -0,0 +1,457 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Advent of Code 2017\n",
|
||||||
|
"\n",
|
||||||
|
"## December 6th\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
" [0 2 7 0] dup max\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from notebook_preamble import D, J, V, define"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": true
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[0 2 7 0] 7\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[0 2 7 0] dup max')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from joy.library import SimpleFunctionWrapper\n",
|
||||||
|
"from joy.utils.stack import list_to_stack\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"@SimpleFunctionWrapper\n",
|
||||||
|
"def index_of(stack):\n",
|
||||||
|
" '''Given a sequence and a item, return the index of the item, or -1 if not found.\n",
|
||||||
|
"\n",
|
||||||
|
" E.g.:\n",
|
||||||
|
"\n",
|
||||||
|
" [a b c] a index_of\n",
|
||||||
|
" ------------------------\n",
|
||||||
|
" 0\n",
|
||||||
|
"\n",
|
||||||
|
" [a b c] d index_of\n",
|
||||||
|
" ------------------------\n",
|
||||||
|
" -1\n",
|
||||||
|
"\n",
|
||||||
|
" '''\n",
|
||||||
|
" item, (sequence, stack) = stack\n",
|
||||||
|
" i = 0\n",
|
||||||
|
" while sequence:\n",
|
||||||
|
" term, sequence = sequence\n",
|
||||||
|
" if term == item:\n",
|
||||||
|
" break\n",
|
||||||
|
" i += 1\n",
|
||||||
|
" else:\n",
|
||||||
|
" i = -1\n",
|
||||||
|
" return i, stack\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"D['index_of'] = index_of"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"2\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[0 2 7 0] 7 index_of')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"-1\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[0 2 7 0] 23 index_of')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Starting at `index` distribute `count` \"blocks\" to the \"banks\" in the sequence.\n",
|
||||||
|
"\n",
|
||||||
|
" [...] count index distribute\n",
|
||||||
|
" ----------------------------\n",
|
||||||
|
" [...]\n",
|
||||||
|
"\n",
|
||||||
|
"This seems like it would be a PITA to implement in Joypy..."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from joy.utils.stack import iter_stack, list_to_stack\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"@SimpleFunctionWrapper\n",
|
||||||
|
"def distribute(stack):\n",
|
||||||
|
" '''Starting at index+1 distribute count \"blocks\" to the \"banks\" in the sequence.\n",
|
||||||
|
"\n",
|
||||||
|
" [...] count index distribute\n",
|
||||||
|
" ----------------------------\n",
|
||||||
|
" [...]\n",
|
||||||
|
"\n",
|
||||||
|
" '''\n",
|
||||||
|
" index, (count, (sequence, stack)) = stack\n",
|
||||||
|
" assert count >= 0\n",
|
||||||
|
" cheat = list(iter_stack(sequence))\n",
|
||||||
|
" n = len(cheat)\n",
|
||||||
|
" assert index < n\n",
|
||||||
|
" cheat[index] = 0\n",
|
||||||
|
" while count:\n",
|
||||||
|
" index += 1\n",
|
||||||
|
" index %= n\n",
|
||||||
|
" cheat[index] += 1\n",
|
||||||
|
" count -= 1\n",
|
||||||
|
" return list_to_stack(cheat), stack\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"D['distribute'] = distribute"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[2 4 1 2]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[0 2 7 0] dup max [index_of] nullary distribute')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[3 1 2 3]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[2 4 1 2] dup max [index_of] nullary distribute')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[0 2 3 4]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[3 1 2 3] dup max [index_of] nullary distribute')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1 3 4 1]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[0 2 3 4] dup max [index_of] nullary distribute')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[2 4 1 2]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 3 4 1] dup max [index_of] nullary distribute')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Recalling \"Generator Programs\"\n",
|
||||||
|
"\n",
|
||||||
|
" [a F] x\n",
|
||||||
|
" [a F] a F \n",
|
||||||
|
" \n",
|
||||||
|
" [a F] a swap [C] dip rest cons\n",
|
||||||
|
" a [a F] [C] dip rest cons\n",
|
||||||
|
" a C [a F] rest cons\n",
|
||||||
|
" a C [F] cons\n",
|
||||||
|
"\n",
|
||||||
|
" w/ C == dup G\n",
|
||||||
|
"\n",
|
||||||
|
" a dup G [F] cons\n",
|
||||||
|
" a a G [F] cons\n",
|
||||||
|
"\n",
|
||||||
|
" w/ G == dup max [index_of] nullary distribute"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 12,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('direco == dip rest cons')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 13,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('G == [direco] cons [swap] swoncat cons')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 14,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('make_distributor == [dup dup max [index_of] nullary distribute] G')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 15,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[0 2 7 0] [2 4 1 2] [3 1 2 3] [0 2 3 4] [1 3 4 1] [2 4 1 2]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[0 2 7 0] make_distributor 6 [x] times pop')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### A function to drive a generator and count how many states before a repeat.\n",
|
||||||
|
"First draft:\n",
|
||||||
|
"\n",
|
||||||
|
" [] [GEN] x [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec\n",
|
||||||
|
"\n",
|
||||||
|
"(?)\n",
|
||||||
|
"\n",
|
||||||
|
" [] [GEN] x [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec\n",
|
||||||
|
" [] [...] [GEN] [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec\n",
|
||||||
|
" [] [...] [GEN] pop index_of 0 >=\n",
|
||||||
|
" [] [...] index_of 0 >=\n",
|
||||||
|
" -1 0 >=\n",
|
||||||
|
" False\n",
|
||||||
|
"\n",
|
||||||
|
"Base case\n",
|
||||||
|
"\n",
|
||||||
|
" [] [...] [GEN] [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec\n",
|
||||||
|
" [] [...] [GEN] pop size --\n",
|
||||||
|
" [] [...] size --\n",
|
||||||
|
" [] [...] size --\n",
|
||||||
|
"\n",
|
||||||
|
"A mistake, `popop` and no need for `--`\n",
|
||||||
|
"\n",
|
||||||
|
" [] [...] [GEN] popop size\n",
|
||||||
|
" [] size\n",
|
||||||
|
" n\n",
|
||||||
|
"\n",
|
||||||
|
"Recursive case\n",
|
||||||
|
"\n",
|
||||||
|
" [] [...] [GEN] [pop index_of 0 >=] [popop size] [[swons] dip x] primrec\n",
|
||||||
|
" [] [...] [GEN] [swons] dip x F\n",
|
||||||
|
" [] [...] swons [GEN] x F\n",
|
||||||
|
" [[...]] [GEN] x F\n",
|
||||||
|
" [[...]] [...] [GEN] F\n",
|
||||||
|
"\n",
|
||||||
|
" [[...]] [...] [GEN] F\n",
|
||||||
|
"\n",
|
||||||
|
"What have we learned?\n",
|
||||||
|
"\n",
|
||||||
|
" F == [pop index_of 0 >=] [popop size] [[swons] dip x] primrec"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 16,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('count_states == [] swap x [pop index_of 0 >=] [popop size] [[swons] dip x] primrec')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 17,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('AoC2017.6 == make_distributor count_states')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 18,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"5\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[0 2 7 0] AoC2017.6')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 19,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": false
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"4\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 1 1] AoC2017.6')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 20,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": false
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"15\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[8 0 0 0 0 0] AoC2017.6')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 2",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python2"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 2
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython2",
|
||||||
|
"version": "2.7.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,267 @@
|
||||||
|
|
||||||
|
# Advent of Code 2017
|
||||||
|
|
||||||
|
## December 6th
|
||||||
|
|
||||||
|
|
||||||
|
[0 2 7 0] dup max
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from notebook_preamble import D, J, V, define
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[0 2 7 0] dup max')
|
||||||
|
```
|
||||||
|
|
||||||
|
[0 2 7 0] 7
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from joy.library import SimpleFunctionWrapper
|
||||||
|
from joy.utils.stack import list_to_stack
|
||||||
|
|
||||||
|
|
||||||
|
@SimpleFunctionWrapper
|
||||||
|
def index_of(stack):
|
||||||
|
'''Given a sequence and a item, return the index of the item, or -1 if not found.
|
||||||
|
|
||||||
|
E.g.:
|
||||||
|
|
||||||
|
[a b c] a index_of
|
||||||
|
------------------------
|
||||||
|
0
|
||||||
|
|
||||||
|
[a b c] d index_of
|
||||||
|
------------------------
|
||||||
|
-1
|
||||||
|
|
||||||
|
'''
|
||||||
|
item, (sequence, stack) = stack
|
||||||
|
i = 0
|
||||||
|
while sequence:
|
||||||
|
term, sequence = sequence
|
||||||
|
if term == item:
|
||||||
|
break
|
||||||
|
i += 1
|
||||||
|
else:
|
||||||
|
i = -1
|
||||||
|
return i, stack
|
||||||
|
|
||||||
|
|
||||||
|
D['index_of'] = index_of
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[0 2 7 0] 7 index_of')
|
||||||
|
```
|
||||||
|
|
||||||
|
2
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[0 2 7 0] 23 index_of')
|
||||||
|
```
|
||||||
|
|
||||||
|
-1
|
||||||
|
|
||||||
|
|
||||||
|
Starting at `index` distribute `count` "blocks" to the "banks" in the sequence.
|
||||||
|
|
||||||
|
[...] count index distribute
|
||||||
|
----------------------------
|
||||||
|
[...]
|
||||||
|
|
||||||
|
This seems like it would be a PITA to implement in Joypy...
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from joy.utils.stack import iter_stack, list_to_stack
|
||||||
|
|
||||||
|
|
||||||
|
@SimpleFunctionWrapper
|
||||||
|
def distribute(stack):
|
||||||
|
'''Starting at index+1 distribute count "blocks" to the "banks" in the sequence.
|
||||||
|
|
||||||
|
[...] count index distribute
|
||||||
|
----------------------------
|
||||||
|
[...]
|
||||||
|
|
||||||
|
'''
|
||||||
|
index, (count, (sequence, stack)) = stack
|
||||||
|
assert count >= 0
|
||||||
|
cheat = list(iter_stack(sequence))
|
||||||
|
n = len(cheat)
|
||||||
|
assert index < n
|
||||||
|
cheat[index] = 0
|
||||||
|
while count:
|
||||||
|
index += 1
|
||||||
|
index %= n
|
||||||
|
cheat[index] += 1
|
||||||
|
count -= 1
|
||||||
|
return list_to_stack(cheat), stack
|
||||||
|
|
||||||
|
|
||||||
|
D['distribute'] = distribute
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[0 2 7 0] dup max [index_of] nullary distribute')
|
||||||
|
```
|
||||||
|
|
||||||
|
[2 4 1 2]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[2 4 1 2] dup max [index_of] nullary distribute')
|
||||||
|
```
|
||||||
|
|
||||||
|
[3 1 2 3]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[3 1 2 3] dup max [index_of] nullary distribute')
|
||||||
|
```
|
||||||
|
|
||||||
|
[0 2 3 4]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[0 2 3 4] dup max [index_of] nullary distribute')
|
||||||
|
```
|
||||||
|
|
||||||
|
[1 3 4 1]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 3 4 1] dup max [index_of] nullary distribute')
|
||||||
|
```
|
||||||
|
|
||||||
|
[2 4 1 2]
|
||||||
|
|
||||||
|
|
||||||
|
### Recalling "Generator Programs"
|
||||||
|
|
||||||
|
[a F] x
|
||||||
|
[a F] a F
|
||||||
|
|
||||||
|
[a F] a swap [C] dip rest cons
|
||||||
|
a [a F] [C] dip rest cons
|
||||||
|
a C [a F] rest cons
|
||||||
|
a C [F] cons
|
||||||
|
|
||||||
|
w/ C == dup G
|
||||||
|
|
||||||
|
a dup G [F] cons
|
||||||
|
a a G [F] cons
|
||||||
|
|
||||||
|
w/ G == dup max [index_of] nullary distribute
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('direco == dip rest cons')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('G == [direco] cons [swap] swoncat cons')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('make_distributor == [dup dup max [index_of] nullary distribute] G')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[0 2 7 0] make_distributor 6 [x] times pop')
|
||||||
|
```
|
||||||
|
|
||||||
|
[0 2 7 0] [2 4 1 2] [3 1 2 3] [0 2 3 4] [1 3 4 1] [2 4 1 2]
|
||||||
|
|
||||||
|
|
||||||
|
### A function to drive a generator and count how many states before a repeat.
|
||||||
|
First draft:
|
||||||
|
|
||||||
|
[] [GEN] x [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec
|
||||||
|
|
||||||
|
(?)
|
||||||
|
|
||||||
|
[] [GEN] x [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec
|
||||||
|
[] [...] [GEN] [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec
|
||||||
|
[] [...] [GEN] pop index_of 0 >=
|
||||||
|
[] [...] index_of 0 >=
|
||||||
|
-1 0 >=
|
||||||
|
False
|
||||||
|
|
||||||
|
Base case
|
||||||
|
|
||||||
|
[] [...] [GEN] [pop index_of 0 >=] [pop size --] [[swons] dip x] primrec
|
||||||
|
[] [...] [GEN] pop size --
|
||||||
|
[] [...] size --
|
||||||
|
[] [...] size --
|
||||||
|
|
||||||
|
A mistake, `popop` and no need for `--`
|
||||||
|
|
||||||
|
[] [...] [GEN] popop size
|
||||||
|
[] size
|
||||||
|
n
|
||||||
|
|
||||||
|
Recursive case
|
||||||
|
|
||||||
|
[] [...] [GEN] [pop index_of 0 >=] [popop size] [[swons] dip x] primrec
|
||||||
|
[] [...] [GEN] [swons] dip x F
|
||||||
|
[] [...] swons [GEN] x F
|
||||||
|
[[...]] [GEN] x F
|
||||||
|
[[...]] [...] [GEN] F
|
||||||
|
|
||||||
|
[[...]] [...] [GEN] F
|
||||||
|
|
||||||
|
What have we learned?
|
||||||
|
|
||||||
|
F == [pop index_of 0 >=] [popop size] [[swons] dip x] primrec
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('count_states == [] swap x [pop index_of 0 >=] [popop size] [[swons] dip x] primrec')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('AoC2017.6 == make_distributor count_states')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[0 2 7 0] AoC2017.6')
|
||||||
|
```
|
||||||
|
|
||||||
|
5
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 1 1] AoC2017.6')
|
||||||
|
```
|
||||||
|
|
||||||
|
4
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[8 0 0 0 0 0] AoC2017.6')
|
||||||
|
```
|
||||||
|
|
||||||
|
15
|
||||||
|
|
||||||
|
|
@ -0,0 +1,469 @@
|
||||||
|
|
||||||
|
# Joy
|
||||||
|
|
||||||
|
This document is written to capture, at least crudely, the scope of application for Joy and the Joypy implementation. It kind of expects that you have some familiarity with Joy already.
|
||||||
|
|
||||||
|
It is vaguely organized, in a pile.
|
||||||
|
|
||||||
|
|
||||||
|
## Syntax
|
||||||
|
|
||||||
|
Very simple syntax. Could be specified as a sequence of one or more terms:
|
||||||
|
|
||||||
|
joy ::= term term*
|
||||||
|
|
||||||
|
Conceptually, all terms are unary functions `F :: stack -> stack` that accept a stack and return a stack. But we immediately differentiate between literals (of a few kinds), functions, and combinators (which like higher-order functions.)
|
||||||
|
|
||||||
|
|
||||||
|
### In Joypy there are currently four literal types.
|
||||||
|
|
||||||
|
First we have the types borrowed from the underlying Python semantics. **Strings** (byte and Unicode with nuances depending on whether you're running under Python 2 or 3), **ints**, and **floats**. Then there is the **sequence** type, aka "quote", "list", etc... In joy it is represented by enclosing zero or more terms in square brackets:
|
||||||
|
|
||||||
|
sequence :== '[' term* ']'
|
||||||
|
|
||||||
|
(In Joypy it is implemented as a cons-list. All datastructures in Joypy are built out of this single sequence type, including the stack and expression. I could include Python `frozenset` but I don't.)
|
||||||
|
|
||||||
|
literal ::= string | int | float | sequence
|
||||||
|
|
||||||
|
Functions accept zero or more arguments from the stack and push back zero or more results.
|
||||||
|
|
||||||
|
Combinators are functions one or more of the arguments to which are quotes containing joy expressions, and which then execute one or more of their quoted arguments to effect their function.
|
||||||
|
|
||||||
|
term ::= literal | function | combinator
|
||||||
|
|
||||||
|
The code for the parser is in `joy/parser.py`.
|
||||||
|
|
||||||
|
|
||||||
|
## Semantics
|
||||||
|
|
||||||
|
In Joy juxtaposition of symbols is composition of functions. That means that `F G` syntactically is `G(F(...))` semantically.
|
||||||
|
|
||||||
|
As it says in the [Wikipedia entry for Joypy](https://en.wikipedia.org/wiki/Joy_%28programming_language%29):
|
||||||
|
|
||||||
|
"In Joy, the meaning function is a homomorphism from the syntactic monoid onto the semantic monoid. That is, the syntactic relation of concatenation of symbols maps directly onto the semantic relation of composition of functions."
|
||||||
|
|
||||||
|
Isn't that nice?
|
||||||
|
|
||||||
|
|
||||||
|
## Joypy Continuation-Passing Style
|
||||||
|
|
||||||
|
In Joypy all the combinators work by modifying the pending expression. We have enlarged the definition of function to be from a two-tuple of `(stack, expression)` to another such two-tuple:
|
||||||
|
|
||||||
|
F :: (stack, expression) -> (stack, expression)
|
||||||
|
|
||||||
|
Simple functions ignore the expression and pass it through unchanged, combinators do not. They can modify it and this is enough to define control-flow and other operators.
|
||||||
|
|
||||||
|
(Actually... In Joypy the functions all also include a dictionary parameter. This allows for functions like `print_words` and `help`. It also allows for the definition of a `define` function which would let Joy code add new definitions to the dictionary during evaluation, but this is an area I am leaving unexplored at least for now. It is essentially name-binding (variables) sneaking in, breaking the purity of the system.)
|
||||||
|
|
||||||
|
|
||||||
|
## Evaluation
|
||||||
|
|
||||||
|
The joy interpreter is a very simple loop. As long as the expression is non-empty the interpreter pops the next term and checks it, if it's a literal it's pushed onto the stack, if it's a function or combinator the interpreter calls it passing the current stack and expression, which are then replaced by whatever the function or combinator returns.
|
||||||
|
|
||||||
|
There is no call stack. All state is kept either on the stack or in the pending expression. At each interpreter iteration the stack and expression are complete. (They can be pickled, saved to disc or sent over the network, and reconstituted at any time, etc...)
|
||||||
|
|
||||||
|
|
||||||
|
# Methods of Meta-programming
|
||||||
|
|
||||||
|
Joy seems to lend itself to several complementary forms of meta-programming to develop more-efficient versions of functions.
|
||||||
|
|
||||||
|
|
||||||
|
## Compiling definitions.
|
||||||
|
|
||||||
|
Due to the fact that "juxtaposition of symbols is composition of functions" the *simplest* way to "compile" the Joy expression `F G` would be the Python expression:
|
||||||
|
|
||||||
|
lambda s, e, d: G(*F(s, e, d))
|
||||||
|
|
||||||
|
This produces a new unnamed function that delivers the output of `F` directly to `G` without passing back through the interpreter loop.
|
||||||
|
|
||||||
|
If we wanted to do more work than that, we could inspect the bytecode of the two Python functions, figure out how they name their arguments, and attempt to produce new bytecode that corresponds to the composition of them. This is a little beyond me at the moment, but it's not unrealistic given enough time and attention.
|
||||||
|
|
||||||
|
It will usually be easier to manually write new custom words. For example, the "plus or minus" operator `pm`, defined as:
|
||||||
|
|
||||||
|
pm == [+] [-] cleave popdd
|
||||||
|
|
||||||
|
Can be implemented in Python as:
|
||||||
|
|
||||||
|
@SimpleFunctionWrapper
|
||||||
|
def pm(stack):
|
||||||
|
a, (b, stack) = stack
|
||||||
|
p = b + a
|
||||||
|
m = b - a
|
||||||
|
return m, (p, stack)
|
||||||
|
|
||||||
|
Code that uses `pm` will will work the same but more quickly if the "compiled" version is inscribed in the dictionary.
|
||||||
|
|
||||||
|
It would be remiss not to mention **Cython** in this connection. Many Joy functions can be transparently compiled down to machine code.
|
||||||
|
|
||||||
|
Beyond the above, it should be possible to make use of much of the existing body of knowledge for compiling *functional programming* languages to machine code for making an actual Joy compiler. Joy omits many "features" that are common to most other languages, lambda abstraction and `let` statements for example. I have not had the time to investigate compilation of Joy in any depth so far, but I have high hopes. It should be possible (and most of the details will have been already worked out in other languages) to go from e.g. the definition form of `pm` to the Python form automatically.
|
||||||
|
|
||||||
|
|
||||||
|
## Partial Evaluation
|
||||||
|
|
||||||
|
Cf. "Futamura projections"
|
||||||
|
|
||||||
|
["partial evaluation is a technique for several different types of program optimization by specialization. The most straightforward application is to produce new programs which run faster than the originals while being guaranteed to behave in the same way."](https://en.wikipedia.org/wiki/Partial_evaluation) ~Wikipedia
|
||||||
|
|
||||||
|
Given a function and some (but not all) of its arguments you can run the interpreter in a speculative fashion and derive new functions that are specializations of the original.
|
||||||
|
|
||||||
|
Example from [Futamura, 1983](https://repository.kulib.kyoto-u.ac.jp/dspace/bitstream/2433/103401/1/0482-14.pdf) of converting a power function to a "to the fifth power" function:
|
||||||
|
|
||||||
|
F(k, u) -> u^k
|
||||||
|
|
||||||
|
I like to use a kind of crude [Gentzen notation](https://en.wikipedia.org/wiki/Natural_deduction) to describe a Joy function's semantics:
|
||||||
|
|
||||||
|
k u F
|
||||||
|
-----------
|
||||||
|
u^k
|
||||||
|
|
||||||
|
Joy function implementation:
|
||||||
|
|
||||||
|
F == 1 [popop 0 !=] [[popop 2 %] [over *] [] ifte [1 >>] dipd [sqr] dip] while [popop] dip
|
||||||
|
|
||||||
|
This is a bit longer than a definition should be. In practice I would refactor it to be more concise and easily understood.
|
||||||
|
|
||||||
|
In Python for comparison:
|
||||||
|
|
||||||
|
def power(k, u):
|
||||||
|
z = 1
|
||||||
|
while k != 0:
|
||||||
|
if k % 2:
|
||||||
|
z = z * u
|
||||||
|
k = k >> 1
|
||||||
|
u = u * u
|
||||||
|
return z
|
||||||
|
|
||||||
|
Using 5 for `k` and pushing evaluation forward as far as it will go with a sort of "thunk" variable for `u` we arrive at:
|
||||||
|
|
||||||
|
u u u * dup * *
|
||||||
|
|
||||||
|
We can replace the extra occurrences of `u` with `dup` to arrive at a definition for a Joy function that, given a number on the stack, returns that number raised to the fifth power:
|
||||||
|
|
||||||
|
to-the-fifth == dup dup * dup * *
|
||||||
|
|
||||||
|
Here it is in action:
|
||||||
|
|
||||||
|
u dup dup * dup * *
|
||||||
|
u u dup * dup * *
|
||||||
|
u u u * dup * *
|
||||||
|
u u^2 dup * *
|
||||||
|
u u^2 u^2 * *
|
||||||
|
u u^4 *
|
||||||
|
u^5
|
||||||
|
|
||||||
|
See the appendix below for the derivation of the specialized form from the general form.
|
||||||
|
|
||||||
|
It should be possible to write a program `FutamuraI` that works like this:
|
||||||
|
|
||||||
|
[5] [F] FutamuraI
|
||||||
|
-------------------------
|
||||||
|
[dup dup * dup * *]
|
||||||
|
|
||||||
|
|
||||||
|
That is, given the quoted program `[F]` and the argument `5`, it returns the new `to-the-fifth` function in quoted form.
|
||||||
|
|
||||||
|
|
||||||
|
### First Futamura Projection
|
||||||
|
|
||||||
|
A joy interpreter written in Joy is described in the literature (available from the La Trobe archive or the mirror site) so we can apply the program `FutamuraI` to that to get a *residual* program `R` for some program `Q`:
|
||||||
|
|
||||||
|
[Q] [joy] FutamuraI
|
||||||
|
-------------------------
|
||||||
|
[R]
|
||||||
|
|
||||||
|
The expected result is that, for a given input, the runtime of `R` is less than or equal to the runtime of `Q`.
|
||||||
|
|
||||||
|
If we had a partial evaluator for Python we could create a residual program in Python for the Joy program `Q`.
|
||||||
|
|
||||||
|
|
||||||
|
### Second Futamura Projection
|
||||||
|
|
||||||
|
[joy] [FutamuraI] FutamuraI
|
||||||
|
---------------------------------
|
||||||
|
[C]
|
||||||
|
|
||||||
|
Making a compiler by "specializing the specializer for the interpreter".
|
||||||
|
|
||||||
|
|
||||||
|
### Third Futamura Projection
|
||||||
|
|
||||||
|
[FutamuraI] [FutamuraI] FutamuraI
|
||||||
|
---------------------------------------
|
||||||
|
[K]
|
||||||
|
|
||||||
|
"Specializing the specializer for itself yielding a tool that can convert any interpreter to an equivalent compiler"
|
||||||
|
|
||||||
|
[joy] K
|
||||||
|
-------------
|
||||||
|
[C]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
[Q] [joy] K i
|
||||||
|
-------------------
|
||||||
|
[Q] C
|
||||||
|
-----------
|
||||||
|
[R]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
[K] K -> [K]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Super-Compilation
|
||||||
|
|
||||||
|
https://en.wikipedia.org/wiki/Metacompilation
|
||||||
|
|
||||||
|
https://themonadreader.files.wordpress.com/2014/04/super-final.pdf
|
||||||
|
|
||||||
|
This is a little hard to describe succinctly, but you are basically trying to figure out all possible paths through a program and then use that knowledge to improve the code, somehow. (I forget the details, but it's worth including and revisiting.)
|
||||||
|
|
||||||
|
|
||||||
|
## Gödel Machine
|
||||||
|
|
||||||
|
http://people.idsia.ch/~juergen/goedelmachine.html
|
||||||
|
|
||||||
|
https://en.wikipedia.org/wiki/G%C3%B6del_machine
|
||||||
|
|
||||||
|
In Joy it often happens that a new general form is discovered that is semantically equivalent to some other form but that has greater efficiency (at least under some definite conditions.) When this happens we can perform a kind of search-and-replace operation over the whole of the current dictionary (standard library in other languages) and achieve performance gains.
|
||||||
|
|
||||||
|
As an example, the function `[1 >>] dipd [sqr] dip` can be rewritten as `[[1 >>] dip sqr] dip` which, depending on the other optimizations some interpreter might make, could be more efficient. We can generalize this to a pattern-matching rule, something like:
|
||||||
|
|
||||||
|
[F] dipd [G] dip == [[F] dip G] dip
|
||||||
|
|
||||||
|
And we are justified rewriting any occurrence of the pattern on either side to the other if it improves things.
|
||||||
|
|
||||||
|
The above also suggests a new combinator, call it `dipdip` that abstracts the pattern:
|
||||||
|
|
||||||
|
... a b [F] [G] dipdip
|
||||||
|
----------------------------
|
||||||
|
... F a G b
|
||||||
|
|
||||||
|
This permits the compiler to make optimizations without having to work to notice the pattern. The `dipdip` function and the interpreter can work together to do the more efficient thing.
|
||||||
|
|
||||||
|
Joy function definitions form Directed Graphs. Not acyclical though, definition bodies do not contain references to other functions, but rather "Symbols" that name functions, so you can form e.g. two definitions that each make use of the other. Generally speaking though, you don't do this, instead you write definitions that use e.g. `genrec` general recursion combinator.
|
||||||
|
|
||||||
|
Anyway, because Joy code is just a graph it becomes pretty easy to rewrite the graph in ways that preserve the semantics but are more efficient. Doing this in an automated fashion is essentially Schmidhuber's Gödel Machine: Finding and applying provably-correct modifications to the whole system in a self-referential way to create a self-improving general problem solver.
|
||||||
|
|
||||||
|
Joy is intended as an effective vehicle for exploring this potential.
|
||||||
|
|
||||||
|
|
||||||
|
## Speculative pre-evaluation
|
||||||
|
|
||||||
|
If you examine the traces of Joy programs it's easy to find places in the pending expression where some speculative interpreter could pre-compute results while the main interpreter was prosecuting the main "thread" of the program. For example consider (with the `.` indicating the current "location of the interpreter head" if you will, the split between the stack and the expression):
|
||||||
|
|
||||||
|
... a b c . F 2 3 + G H
|
||||||
|
|
||||||
|
The `2 3 +` between `F` and `G` is not at the interpreter "head" yet it is extremely unlikely that any function `F` will prevent it (eventually) being evaluated to `5`. We can imagine an interpreter that detects this sort of thing, evaluates the sub-expression with a different CPU, and "tags" the expression at `2` with the result `5`. If evaluation reaches `2` the interpreter can just use `5` without re-evaluating the whole sub-expression `2 3 +`.
|
||||||
|
|
||||||
|
This sort of thing happens all the time in Joy code.
|
||||||
|
|
||||||
|
For example, if you look at the appendix for the partial evaluation example there is a stage where we have this:
|
||||||
|
|
||||||
|
5 u u [1 >>] dipd [sqr] dip
|
||||||
|
|
||||||
|
Which can be written with the `dipdip` combinator:
|
||||||
|
|
||||||
|
5 u u [1 >>] [sqr] dipdip
|
||||||
|
|
||||||
|
Which then becomes this:
|
||||||
|
|
||||||
|
5 1 >> u sqr u
|
||||||
|
|
||||||
|
The interpreter could notice that `5 1 >>` and `u sqr` can proceed in parallel without interfering with each other. The `dipdip` combinator could be written to somehow hint to the interpreter that it should check for this posibility.
|
||||||
|
|
||||||
|
|
||||||
|
## JIT
|
||||||
|
|
||||||
|
Whatever eventually winds up converting Joy code to machine code is susceptible to Just-in-Time compilation. For example, if you run Joypy on Pypy you take advantage of its JIT.
|
||||||
|
|
||||||
|
|
||||||
|
# Joy as UI
|
||||||
|
|
||||||
|
|
||||||
|
## Joy unifies CLI and GUI interfaces.
|
||||||
|
|
||||||
|
All Joy interaction consists of two basic actions:
|
||||||
|
|
||||||
|
1. Putting things onto the stack.
|
||||||
|
2. Executing functions.
|
||||||
|
|
||||||
|
In a command-line setting you perform both of these actions the same way: entering Joy expressions as text. In a GUI you select items and copy or cut them to a user-visible stack (that is a first-class member of the UI, similar to the clipboard but with better visibility into contents and not restricted to one selection at a time.) You then trigger the evaluation of functions by clicking on buttons or menu items. *From the point-of-view of the underlying interpreter there is no difference between the input token streams for either UI modality.*
|
||||||
|
|
||||||
|
|
||||||
|
## Simple and Comprehensible Model
|
||||||
|
|
||||||
|
In order to use their system(s) users must be able to easily and quickly develop a mental model of the system that maps to the actual system abstractions well enough to support the achievement of their goals.
|
||||||
|
|
||||||
|
(Arguably current systems are pretty poor at this. Even an abstraction as old and ubiquitous as "filesystem" is only incompletely understood by many computer users. Many people do not understand the difference between RAM and disk storage!)
|
||||||
|
|
||||||
|
The Joy model consists of just these main concepts:
|
||||||
|
|
||||||
|
1. A stack of values
|
||||||
|
2. A dictionary of named commands
|
||||||
|
3. An interpreter
|
||||||
|
|
||||||
|
Each of these is very simple and the first two even have real-world analogs (e.g. a *stack* of dishes or boxes or whatever, and, well, *dictionaries*.) It's easy to develop intuition for this system, resulting in a close match between the user's mental model and the actual system abstraction.
|
||||||
|
|
||||||
|
|
||||||
|
# Joy as AST for multi-language interop
|
||||||
|
|
||||||
|
IR for Compilation
|
||||||
|
|
||||||
|
Cf. Graal & Truffle
|
||||||
|
|
||||||
|
"Software is eating the world"; Joy eats software.
|
||||||
|
|
||||||
|
Universal Solvent
|
||||||
|
|
||||||
|
Can write front-ends for translating other languages into Joy, thence to be refactored and fulminated into more efficient forms. "The Blob" of software.
|
||||||
|
|
||||||
|
|
||||||
|
# Minimal Basis
|
||||||
|
|
||||||
|
Cf. SKI combinators, Peano arithmentic, Church numerals et. al.,
|
||||||
|
|
||||||
|
Folks have done work on figuring out the minimal set of combinators that are Turing-complete. Several of these sets are quite small.
|
||||||
|
|
||||||
|
Semantics can be defined in terms of Laws of Form for down-to-the-metal modeling of programs as logic circuits. Hardware description language.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Math, Physics, Computation
|
||||||
|
|
||||||
|
Computational algorithms are used to communicate precisely
|
||||||
|
some of the methods used in the analysis of dynamical phenomena.
|
||||||
|
Expressing the methods of variational mechanics in a computer
|
||||||
|
language forces them to be unambiguous and computationally
|
||||||
|
effective. Computation requires us to be precise about the repre-
|
||||||
|
sentation of mechanical and geometric notions as computational
|
||||||
|
objects and permits us to represent explicitly the algorithms for
|
||||||
|
manipulating these objects. Also, once formalized as a procedure,
|
||||||
|
a mathematical idea becomes a tool that can be used directly to
|
||||||
|
compute results.
|
||||||
|
- "Structure and Interpretation of Classical Mechanics",
|
||||||
|
Gerald Jay Sussman and Jack Wisdom with Meinhard E. Mayer
|
||||||
|
|
||||||
|
.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Joy as glue language
|
||||||
|
|
||||||
|
Basically any existing code/programs can be exposed to Joy as a function or collection of functions.
|
||||||
|
|
||||||
|
## Shell command
|
||||||
|
|
||||||
|
Run a shell command.
|
||||||
|
|
||||||
|
"stdin" "cmd line" system
|
||||||
|
-----------------------------------
|
||||||
|
"stderr" "stdout" return_code
|
||||||
|
|
||||||
|
Then you can create e.g.:
|
||||||
|
|
||||||
|
foo == "awk {awk program}" system
|
||||||
|
|
||||||
|
Etc...
|
||||||
|
|
||||||
|
## Python libraries
|
||||||
|
|
||||||
|
## Ctypes (FFI) for loading binary libraries
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Git as File Store
|
||||||
|
|
||||||
|
The old-fashioned File System abstraction is no longer justified. Joypy won't attempt to implement file and path operations. Instead there are a few functions that accept three args: a sha1 checksum of a blob of data, an initial index, and an offset. One function returns the string of data `blob[index:index+offset]`, while another accepts an additional quoted program and "runs it" with the data as the stack, for when you want to process a big ol' pile of data but don't want to load it into the interpreter. I imagine a use case for a third-party wrapped library that expects some sort of file or socket and streams over it somehow. Obviously, this is under-specified.
|
||||||
|
|
||||||
|
The sha1 checksum refers to data stored in some (global, universal) git repo, which is provided to the interpreter though some as-yet unimplemented meta-interpreter action.
|
||||||
|
|
||||||
|
**Git is a functional data type**, compatible with the semantic model of Joy. Implies shared datastore with obvious connection to git-archive & Datalad.
|
||||||
|
|
||||||
|
Functions over static data (Wikipedia dump; MRI data &c.) can be considered timeless (however much time their first evaluation takes) and cached/archived in the global shared git repo. (Large data in e.g. cloud & bittorrent, with meta-data in git-archive/Datalad)
|
||||||
|
|
||||||
|
Functions over streams (of possible mal-formed) data require a special stream-processing combinator and more care in their development. I haven't developed this in any detail, but it can be shown in many cases that e.g. a given function cannot grow unbounded (for all possible unbounded input streams.)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Sympy Library
|
||||||
|
|
||||||
|
The mathematical functions in the Joypy library wrap the `math` module and other built-ins for the most part. It would be a simple matter to write wrapper functions for e.g. the Sympy packages' functions and provide symbolic math capabilities.
|
||||||
|
|
||||||
|
It would also be possible to make a dictionary that mapped the math functions to the Sympy versions. Evaluating Joy code with this dictionary (and a special stack with Sympy variables on it) would result in symbolic execution without rewriting the Joy code.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Stack-based laguages as Dataflow
|
||||||
|
|
||||||
|
If the "places" in a stack are considered first-class entities and tracked through "stack chatter" operations (like `swap`) we can draw flow-lines for the data and represent the functions as boxes with input and output lines. Stack chatter becomes topological rearrangements of lines. The resulting structure is conceptually identical with *Dataflow* paradigm of programming.
|
||||||
|
|
||||||
|
(Related to this I suspect that all stack chatter disappears during compilation but I haven't nailed that down yet.)
|
||||||
|
|
||||||
|
I'm unable to find the original webpage that describe the above. :-(
|
||||||
|
|
||||||
|
|
||||||
|
# Appendix Partial Evaluation Example
|
||||||
|
|
||||||
|
k u F
|
||||||
|
-----------
|
||||||
|
u^k
|
||||||
|
|
||||||
|
|
||||||
|
k u 1 [popop 0 !=] [[popop odd][over *][]ifte [1 >>] dipd [sqr] dip] while [popop] dip
|
||||||
|
|
||||||
|
F == 1 [popop 0 !=] [[popop odd][over *][]ifte [1 >>] dipd [sqr] dip] while [popop] dip
|
||||||
|
|
||||||
|
5 u 1 [popop 0 !=] [[popop odd][over *][]ifte [1 >>] dipd [sqr] dip] while [popop] dip
|
||||||
|
|
||||||
|
|
||||||
|
5 u 1 popop 0 !=
|
||||||
|
5 0 !=
|
||||||
|
True
|
||||||
|
|
||||||
|
|
||||||
|
5 u 1 [popop odd][over *][]ifte [1 >>] dipd [sqr] dip
|
||||||
|
5 u 1 popop odd
|
||||||
|
True
|
||||||
|
|
||||||
|
w/ sqr == dup *
|
||||||
|
|
||||||
|
5 u 1 over * [1 >>] dipd [sqr] dip
|
||||||
|
5 u 1 u * [1 >>] dipd [sqr] dip
|
||||||
|
5 u u [1 >>] dipd [sqr] dip
|
||||||
|
5 1 >> u sqr u
|
||||||
|
2 u_dup_* u
|
||||||
|
--or--
|
||||||
|
2 u_u_* u
|
||||||
|
|
||||||
|
2 u_u_* u popop 0 !=
|
||||||
|
2 0 !=
|
||||||
|
True
|
||||||
|
|
||||||
|
2 u_u_* u [popop odd][over *][]ifte [1 >>] dipd [sqr] dip
|
||||||
|
...
|
||||||
|
2 u_u_* u [1 >>] dipd [sqr] dip
|
||||||
|
|
||||||
|
2 1 >> u_u_* sqr u
|
||||||
|
1 u_u_*_dup_* u
|
||||||
|
|
||||||
|
|
||||||
|
1 u_u_*_dup_* u [popop odd][over *][]ifte [1 >>] dipd [sqr] dip
|
||||||
|
1 u_u_*_dup_* u over * [1 >>] dipd [sqr] dip
|
||||||
|
1 u_u_*_dup_* u u_u_*_dup_* * [1 >>] dipd [sqr] dip
|
||||||
|
1 u_u_*_dup_* u_u_u_*_dup_*_* [1 >>] dipd [sqr] dip
|
||||||
|
|
||||||
|
1 1 >> u_u_*_dup_* sqr u_u_u_*_dup_*_*
|
||||||
|
0 u_u_*_dup_* dup * u_u_u_*_dup_*_*
|
||||||
|
0 u_u_*_dup_* u_u_*_dup_* * u_u_u_*_dup_*_*
|
||||||
|
0 u_..._* u_u_u_*_dup_*_*
|
||||||
|
|
||||||
|
0 u_..._* u_u_u_*_dup_*_* [popop] dip
|
||||||
|
|
||||||
|
u_u_u_*_dup_*_*
|
||||||
|
|
||||||
|
^5 == dup dup * dup * *
|
||||||
|
|
@ -0,0 +1,998 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Using `x` to Generate Values\n",
|
||||||
|
"\n",
|
||||||
|
"Cf. jp-reprod.html"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from notebook_preamble import J, V, define"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Consider the `x` combinator `x == dup i`:\n",
|
||||||
|
"\n",
|
||||||
|
" [a B] x\n",
|
||||||
|
" [a B] a B\n",
|
||||||
|
"\n",
|
||||||
|
"Let `B` `swap` the `a` with the quote and run some function `[C]` on it.\n",
|
||||||
|
"\n",
|
||||||
|
" [a B] a B\n",
|
||||||
|
" [a B] a swap [C] dip\n",
|
||||||
|
" a [a B] [C] dip\n",
|
||||||
|
" a C [a B]\n",
|
||||||
|
"\n",
|
||||||
|
"Now discard the quoted `a` with `rest` and `cons` the result of `C` on `a` whatever that is:\n",
|
||||||
|
"\n",
|
||||||
|
" aC [a B] rest cons\n",
|
||||||
|
" aC [B] cons\n",
|
||||||
|
" [aC B]\n",
|
||||||
|
"\n",
|
||||||
|
"Altogether, this is the definition of `B`:\n",
|
||||||
|
"\n",
|
||||||
|
" B == swap [C] dip rest cons\n",
|
||||||
|
"\n",
|
||||||
|
"We can create a quoted program that generates the Natural numbers (integers 0, 1, 2, ...) by using `0` for `a` and `[dup ++]` for `[C]`:\n",
|
||||||
|
"\n",
|
||||||
|
" [0 swap [dup ++] dip rest cons]\n",
|
||||||
|
"\n",
|
||||||
|
"Let's try it:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": true
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . [0 swap [dup ++] dip rest cons] x\n",
|
||||||
|
" [0 swap [dup ++] dip rest cons] . x\n",
|
||||||
|
" [0 swap [dup ++] dip rest cons] . 0 swap [dup ++] dip rest cons\n",
|
||||||
|
" [0 swap [dup ++] dip rest cons] 0 . swap [dup ++] dip rest cons\n",
|
||||||
|
" 0 [0 swap [dup ++] dip rest cons] . [dup ++] dip rest cons\n",
|
||||||
|
"0 [0 swap [dup ++] dip rest cons] [dup ++] . dip rest cons\n",
|
||||||
|
" 0 . dup ++ [0 swap [dup ++] dip rest cons] rest cons\n",
|
||||||
|
" 0 0 . ++ [0 swap [dup ++] dip rest cons] rest cons\n",
|
||||||
|
" 0 1 . [0 swap [dup ++] dip rest cons] rest cons\n",
|
||||||
|
" 0 1 [0 swap [dup ++] dip rest cons] . rest cons\n",
|
||||||
|
" 0 1 [swap [dup ++] dip rest cons] . cons\n",
|
||||||
|
" 0 [1 swap [dup ++] dip rest cons] . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('[0 swap [dup ++] dip rest cons] x')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"After one application of `x` the quoted program contains `1` and `0` is below it on the stack."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"0 1 2 3 4\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[0 swap [dup ++] dip rest cons] x x x x x pop')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### `direco`"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('direco == dip rest cons')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . [0 swap [dup ++] direco] x\n",
|
||||||
|
" [0 swap [dup ++] direco] . x\n",
|
||||||
|
" [0 swap [dup ++] direco] . 0 swap [dup ++] direco\n",
|
||||||
|
" [0 swap [dup ++] direco] 0 . swap [dup ++] direco\n",
|
||||||
|
" 0 [0 swap [dup ++] direco] . [dup ++] direco\n",
|
||||||
|
"0 [0 swap [dup ++] direco] [dup ++] . direco\n",
|
||||||
|
"0 [0 swap [dup ++] direco] [dup ++] . dip rest cons\n",
|
||||||
|
" 0 . dup ++ [0 swap [dup ++] direco] rest cons\n",
|
||||||
|
" 0 0 . ++ [0 swap [dup ++] direco] rest cons\n",
|
||||||
|
" 0 1 . [0 swap [dup ++] direco] rest cons\n",
|
||||||
|
" 0 1 [0 swap [dup ++] direco] . rest cons\n",
|
||||||
|
" 0 1 [swap [dup ++] direco] . cons\n",
|
||||||
|
" 0 [1 swap [dup ++] direco] . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('[0 swap [dup ++] direco] x')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Generating Generators\n",
|
||||||
|
"We want to go from:\n",
|
||||||
|
"\n",
|
||||||
|
" a [C] G\n",
|
||||||
|
"\n",
|
||||||
|
"to:\n",
|
||||||
|
"\n",
|
||||||
|
" [a swap [C] direco]\n",
|
||||||
|
"\n",
|
||||||
|
"Working in reverse:\n",
|
||||||
|
"\n",
|
||||||
|
" [a swap [C] direco] cons\n",
|
||||||
|
" a [swap [C] direco] concat\n",
|
||||||
|
" a [swap] [[C] direco] swap\n",
|
||||||
|
" a [[C] direco] [swap]\n",
|
||||||
|
" a [C] [direco] cons [swap]\n",
|
||||||
|
"\n",
|
||||||
|
"Reading from the bottom up:\n",
|
||||||
|
"\n",
|
||||||
|
" G == [direco] cons [swap] swap concat cons\n",
|
||||||
|
" G == [direco] cons [swap] swoncat cons\n",
|
||||||
|
"\n",
|
||||||
|
"We can try it out:\n",
|
||||||
|
"\n",
|
||||||
|
" 0 [dup ++] G"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('G == [direco] cons [swap] swoncat cons')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . 0 [dup ++] G\n",
|
||||||
|
" 0 . [dup ++] G\n",
|
||||||
|
" 0 [dup ++] . G\n",
|
||||||
|
" 0 [dup ++] . [direco] cons [swap] swoncat cons\n",
|
||||||
|
" 0 [dup ++] [direco] . cons [swap] swoncat cons\n",
|
||||||
|
" 0 [[dup ++] direco] . [swap] swoncat cons\n",
|
||||||
|
"0 [[dup ++] direco] [swap] . swoncat cons\n",
|
||||||
|
"0 [[dup ++] direco] [swap] . swap concat cons\n",
|
||||||
|
"0 [swap] [[dup ++] direco] . concat cons\n",
|
||||||
|
" 0 [swap [dup ++] direco] . cons\n",
|
||||||
|
" [0 swap [dup ++] direco] . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('0 [dup ++] G')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . 0 [dup ++] G x\n",
|
||||||
|
" 0 . [dup ++] G x\n",
|
||||||
|
" 0 [dup ++] . G x\n",
|
||||||
|
" 0 [dup ++] . [direco] cons [swap] swoncat cons x\n",
|
||||||
|
" 0 [dup ++] [direco] . cons [swap] swoncat cons x\n",
|
||||||
|
" 0 [[dup ++] direco] . [swap] swoncat cons x\n",
|
||||||
|
" 0 [[dup ++] direco] [swap] . swoncat cons x\n",
|
||||||
|
" 0 [[dup ++] direco] [swap] . swap concat cons x\n",
|
||||||
|
" 0 [swap] [[dup ++] direco] . concat cons x\n",
|
||||||
|
" 0 [swap [dup ++] direco] . cons x\n",
|
||||||
|
" [0 swap [dup ++] direco] . x\n",
|
||||||
|
" [0 swap [dup ++] direco] . 0 swap [dup ++] direco\n",
|
||||||
|
" [0 swap [dup ++] direco] 0 . swap [dup ++] direco\n",
|
||||||
|
" 0 [0 swap [dup ++] direco] . [dup ++] direco\n",
|
||||||
|
"0 [0 swap [dup ++] direco] [dup ++] . direco\n",
|
||||||
|
"0 [0 swap [dup ++] direco] [dup ++] . dip rest cons\n",
|
||||||
|
" 0 . dup ++ [0 swap [dup ++] direco] rest cons\n",
|
||||||
|
" 0 0 . ++ [0 swap [dup ++] direco] rest cons\n",
|
||||||
|
" 0 1 . [0 swap [dup ++] direco] rest cons\n",
|
||||||
|
" 0 1 [0 swap [dup ++] direco] . rest cons\n",
|
||||||
|
" 0 1 [swap [dup ++] direco] . cons\n",
|
||||||
|
" 0 [1 swap [dup ++] direco] . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('0 [dup ++] G x')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Powers of 2"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"1 2 4 8 16 32 64 128 256 [512 swap [dup 1 <<] direco]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('1 [dup 1 <<] G x x x x x x x x x')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# `n [x] times`\n",
|
||||||
|
"If we have one of these quoted programs we can drive it using `times` with the `x` combinator.\n",
|
||||||
|
"\n",
|
||||||
|
"Let's define a word `n_range` that takes a starting integer and a count and leaves that many consecutive integers on the stack. For example:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"23 24 25 26 27\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('23 [dup ++] G 5 [x] times pop')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can use `dip` to untangle `[dup ++] G` from the arguments."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"23 24 25 26 27\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('23 5 [[dup ++] G] dip [x] times pop')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now that the givens (arguments) are on the left we have the definition we're looking for:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 12,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('n_range == [[dup ++] G] dip [x] times pop')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 13,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"450 451 452 453 454 455 456 457 458 459\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('450 10 n_range')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This is better just using the `times` combinator though..."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 14,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": true
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"450 451 452 453 454 455 456 457 458 459\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('450 9 [dup ++] times')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Generating Multiples of Three and Five\n",
|
||||||
|
"Look at the treatment of the Project Euler Problem One in [Developing a Program.ipynb](./Developing a Program.ipynb) and you'll see that we might be interested in generating an endless cycle of:\n",
|
||||||
|
"\n",
|
||||||
|
" 3 2 1 3 1 2 3\n",
|
||||||
|
"\n",
|
||||||
|
"To do this we want to encode the numbers as pairs of bits in a single int:\n",
|
||||||
|
"\n",
|
||||||
|
" 3 2 1 3 1 2 3\n",
|
||||||
|
" 0b 11 10 01 11 01 10 11 == 14811\n",
|
||||||
|
"\n",
|
||||||
|
"And pick them off by masking with 3 (binary 11) and then shifting the int right two bits."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 15,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('PE1.1 == dup [3 &] dip 2 >>')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 16,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . 14811 PE1.1\n",
|
||||||
|
" 14811 . PE1.1\n",
|
||||||
|
" 14811 . dup [3 &] dip 2 >>\n",
|
||||||
|
" 14811 14811 . [3 &] dip 2 >>\n",
|
||||||
|
"14811 14811 [3 &] . dip 2 >>\n",
|
||||||
|
" 14811 . 3 & 14811 2 >>\n",
|
||||||
|
" 14811 3 . & 14811 2 >>\n",
|
||||||
|
" 3 . 14811 2 >>\n",
|
||||||
|
" 3 14811 . 2 >>\n",
|
||||||
|
" 3 14811 2 . >>\n",
|
||||||
|
" 3 3702 . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('14811 PE1.1')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"If we plug `14811` and `[PE1.1]` into our generator form..."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 17,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[14811 swap [PE1.1] direco]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('14811 [PE1.1] G')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 18,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3 [3702 swap [PE1.1] direco]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[14811 swap [PE1.1] direco] x')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"...we get a generator that works for seven cycles before it reaches zero:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 19,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": true
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3 2 1 3 1 2 3 [0 swap [PE1.1] direco]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[14811 swap [PE1.1] direco] 7 [x] times')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Reset at Zero\n",
|
||||||
|
"We need a function that checks if the int has reached zero and resets it if so."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 20,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('PE1.1.check == dup [pop 14811] [] branch')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 21,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"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]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[14811 swap [PE1.1.check PE1.1] direco] 21 [x] times')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Run 466 times\n",
|
||||||
|
"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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 22,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"466\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('7 66 * 4 +')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"If we drive our generator 466 times and sum the stack we get 999."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 23,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": false
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"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] dip rest cons]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[14811 swap [PE1.1.check PE1.1] dip rest cons] 466 [x] times')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 24,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": true
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"999\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[14811 swap [PE1.1.check PE1.1] dip rest cons] 466 [x] times pop enstacken sum')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Project Euler Problem One"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 25,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('PE1.2 == + dup [+] dip')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now we can add `PE1.2` to the quoted program given to `times`."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 26,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"233168\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('0 0 [0 swap [PE1.1.check PE1.1] direco] 466 [x [PE1.2] dip] times popop')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Or using `G` we can write:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 27,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"233168\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('0 0 0 [PE1.1.check PE1.1] G 466 [x [PE1.2] dip] times popop')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# A generator for the Fibonacci Sequence.\n",
|
||||||
|
"Consider:\n",
|
||||||
|
"\n",
|
||||||
|
" [b a F] x\n",
|
||||||
|
" [b a F] b a F\n",
|
||||||
|
"\n",
|
||||||
|
"The obvious first thing to do is just add `b` and `a`:\n",
|
||||||
|
"\n",
|
||||||
|
" [b a F] b a +\n",
|
||||||
|
" [b a F] b+a\n",
|
||||||
|
"\n",
|
||||||
|
"From here we want to arrive at:\n",
|
||||||
|
"\n",
|
||||||
|
" b [b+a b F]\n",
|
||||||
|
"\n",
|
||||||
|
"Let's start with `swons`:\n",
|
||||||
|
"\n",
|
||||||
|
" [b a F] b+a swons\n",
|
||||||
|
" [b+a b a F]\n",
|
||||||
|
"\n",
|
||||||
|
"Considering this quote as a stack:\n",
|
||||||
|
"\n",
|
||||||
|
" F a b b+a\n",
|
||||||
|
"\n",
|
||||||
|
"We want to get it to:\n",
|
||||||
|
"\n",
|
||||||
|
" F b b+a b\n",
|
||||||
|
"\n",
|
||||||
|
"So:\n",
|
||||||
|
"\n",
|
||||||
|
" F a b b+a popdd over\n",
|
||||||
|
" F b b+a b\n",
|
||||||
|
"\n",
|
||||||
|
"And therefore:\n",
|
||||||
|
"\n",
|
||||||
|
" [b+a b a F] [popdd over] infra\n",
|
||||||
|
" [b b+a b F]\n",
|
||||||
|
"\n",
|
||||||
|
"And lastly:\n",
|
||||||
|
"\n",
|
||||||
|
" [b b+a b F] uncons\n",
|
||||||
|
" b [b+a b F]\n",
|
||||||
|
"\n",
|
||||||
|
"Done.\n",
|
||||||
|
"\n",
|
||||||
|
"Putting it all together:\n",
|
||||||
|
"\n",
|
||||||
|
" F == + swons [popdd over] infra uncons\n",
|
||||||
|
"\n",
|
||||||
|
"And:\n",
|
||||||
|
"\n",
|
||||||
|
" fib_gen == [1 1 F]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 28,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('fib == + swons [popdd over] infra uncons')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 29,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('fib_gen == [1 1 fib]')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 30,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"1 2 3 5 8 13 21 34 55 89 [144 89 fib]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('fib_gen 10 [x] times')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Project Euler Problem Two\n",
|
||||||
|
" By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.\n",
|
||||||
|
"\n",
|
||||||
|
"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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 31,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('PE2.1 == dup 2 % [+] [pop] branch')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"And a predicate function that detects when the terms in the series \"exceed four million\"."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 32,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('>4M == 4000000 >')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 33,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('PE2 == 0 fib_gen x [pop >4M] [popop] [[PE2.1] dip x] primrec')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 34,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"4613732\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('PE2')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Here's the collected program definitions:\n",
|
||||||
|
"\n",
|
||||||
|
" fib == + swons [popdd over] infra uncons\n",
|
||||||
|
" fib_gen == [1 1 fib]\n",
|
||||||
|
"\n",
|
||||||
|
" even == dup 2 %\n",
|
||||||
|
" >4M == 4000000 >\n",
|
||||||
|
"\n",
|
||||||
|
" PE2.1 == even [+] [pop] branch\n",
|
||||||
|
" PE2 == 0 fib_gen x [pop >4M] [popop] [[PE2.1] dip x] primrec"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Even-valued Fibonacci Terms\n",
|
||||||
|
"\n",
|
||||||
|
"Using `o` for odd and `e` for even:\n",
|
||||||
|
"\n",
|
||||||
|
" o + o = e\n",
|
||||||
|
" e + e = e\n",
|
||||||
|
" o + e = o\n",
|
||||||
|
"\n",
|
||||||
|
"So the Fibonacci sequence considered in terms of just parity would be:\n",
|
||||||
|
"\n",
|
||||||
|
" o o e o o e o o e o o e o o e o o e\n",
|
||||||
|
" 1 1 2 3 5 8 . . .\n",
|
||||||
|
"\n",
|
||||||
|
"Every third term is even.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 35,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"1 1 2 [3 2 fib]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 0 fib] x x x') # To start the sequence with 1 1 2 3 instead of 1 2 3."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Drive the generator three times and `popop` the two odd terms."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 36,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"2 [3 2 fib]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 0 fib] x x x [popop] dipd')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 37,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('PE2.2 == x x x [popop] dipd')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 38,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"2 8 34 144 610 2584 10946 46368 196418 832040 [1346269 832040 fib]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 0 fib] 10 [PE2.2] times')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Replace `x` with our new driver function `PE2.2` and start our `fib` generator at `1 0`."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 39,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"4613732\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('0 [1 0 fib] PE2.2 [pop >4M] [popop] [[PE2.1] dip PE2.2] primrec')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# How to compile these?\n",
|
||||||
|
"You would probably start with a special version of `G`, and perhaps modifications to the default `x`?"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 2",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python2"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 2
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython2",
|
||||||
|
"version": "2.7.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,538 @@
|
||||||
|
|
||||||
|
# Using `x` to Generate Values
|
||||||
|
|
||||||
|
Cf. jp-reprod.html
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from notebook_preamble import J, V, define
|
||||||
|
```
|
||||||
|
|
||||||
|
Consider the `x` combinator `x == dup i`:
|
||||||
|
|
||||||
|
[a B] x
|
||||||
|
[a B] a B
|
||||||
|
|
||||||
|
Let `B` `swap` the `a` with the quote and run some function `[C]` on it.
|
||||||
|
|
||||||
|
[a B] a B
|
||||||
|
[a B] a swap [C] dip
|
||||||
|
a [a B] [C] dip
|
||||||
|
a C [a B]
|
||||||
|
|
||||||
|
Now discard the quoted `a` with `rest` and `cons` the result of `C` on `a` whatever that is:
|
||||||
|
|
||||||
|
aC [a B] rest cons
|
||||||
|
aC [B] cons
|
||||||
|
[aC B]
|
||||||
|
|
||||||
|
Altogether, this is the definition of `B`:
|
||||||
|
|
||||||
|
B == swap [C] dip rest cons
|
||||||
|
|
||||||
|
We can create a quoted program that generates the Natural numbers (integers 0, 1, 2, ...) by using `0` for `a` and `[dup ++]` for `[C]`:
|
||||||
|
|
||||||
|
[0 swap [dup ++] dip rest cons]
|
||||||
|
|
||||||
|
Let's try it:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('[0 swap [dup ++] dip rest cons] x')
|
||||||
|
```
|
||||||
|
|
||||||
|
. [0 swap [dup ++] dip rest cons] x
|
||||||
|
[0 swap [dup ++] dip rest cons] . x
|
||||||
|
[0 swap [dup ++] dip rest cons] . 0 swap [dup ++] dip rest cons
|
||||||
|
[0 swap [dup ++] dip rest cons] 0 . swap [dup ++] dip rest cons
|
||||||
|
0 [0 swap [dup ++] dip rest cons] . [dup ++] dip rest cons
|
||||||
|
0 [0 swap [dup ++] dip rest cons] [dup ++] . dip rest cons
|
||||||
|
0 . dup ++ [0 swap [dup ++] dip rest cons] rest cons
|
||||||
|
0 0 . ++ [0 swap [dup ++] dip rest cons] rest cons
|
||||||
|
0 1 . [0 swap [dup ++] dip rest cons] rest cons
|
||||||
|
0 1 [0 swap [dup ++] dip rest cons] . rest cons
|
||||||
|
0 1 [swap [dup ++] dip rest cons] . cons
|
||||||
|
0 [1 swap [dup ++] dip rest cons] .
|
||||||
|
|
||||||
|
|
||||||
|
After one application of `x` the quoted program contains `1` and `0` is below it on the stack.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[0 swap [dup ++] dip rest cons] x x x x x pop')
|
||||||
|
```
|
||||||
|
|
||||||
|
0 1 2 3 4
|
||||||
|
|
||||||
|
|
||||||
|
### `direco`
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('direco == dip rest cons')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('[0 swap [dup ++] direco] x')
|
||||||
|
```
|
||||||
|
|
||||||
|
. [0 swap [dup ++] direco] x
|
||||||
|
[0 swap [dup ++] direco] . x
|
||||||
|
[0 swap [dup ++] direco] . 0 swap [dup ++] direco
|
||||||
|
[0 swap [dup ++] direco] 0 . swap [dup ++] direco
|
||||||
|
0 [0 swap [dup ++] direco] . [dup ++] direco
|
||||||
|
0 [0 swap [dup ++] direco] [dup ++] . direco
|
||||||
|
0 [0 swap [dup ++] direco] [dup ++] . dip rest cons
|
||||||
|
0 . dup ++ [0 swap [dup ++] direco] rest cons
|
||||||
|
0 0 . ++ [0 swap [dup ++] direco] rest cons
|
||||||
|
0 1 . [0 swap [dup ++] direco] rest cons
|
||||||
|
0 1 [0 swap [dup ++] direco] . rest cons
|
||||||
|
0 1 [swap [dup ++] direco] . cons
|
||||||
|
0 [1 swap [dup ++] direco] .
|
||||||
|
|
||||||
|
|
||||||
|
# Generating Generators
|
||||||
|
We want to go from:
|
||||||
|
|
||||||
|
a [C] G
|
||||||
|
|
||||||
|
to:
|
||||||
|
|
||||||
|
[a swap [C] direco]
|
||||||
|
|
||||||
|
Working in reverse:
|
||||||
|
|
||||||
|
[a swap [C] direco] cons
|
||||||
|
a [swap [C] direco] concat
|
||||||
|
a [swap] [[C] direco] swap
|
||||||
|
a [[C] direco] [swap]
|
||||||
|
a [C] [direco] cons [swap]
|
||||||
|
|
||||||
|
Reading from the bottom up:
|
||||||
|
|
||||||
|
G == [direco] cons [swap] swap concat cons
|
||||||
|
G == [direco] cons [swap] swoncat cons
|
||||||
|
|
||||||
|
We can try it out:
|
||||||
|
|
||||||
|
0 [dup ++] G
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('G == [direco] cons [swap] swoncat cons')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('0 [dup ++] G')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 0 [dup ++] G
|
||||||
|
0 . [dup ++] G
|
||||||
|
0 [dup ++] . G
|
||||||
|
0 [dup ++] . [direco] cons [swap] swoncat cons
|
||||||
|
0 [dup ++] [direco] . cons [swap] swoncat cons
|
||||||
|
0 [[dup ++] direco] . [swap] swoncat cons
|
||||||
|
0 [[dup ++] direco] [swap] . swoncat cons
|
||||||
|
0 [[dup ++] direco] [swap] . swap concat cons
|
||||||
|
0 [swap] [[dup ++] direco] . concat cons
|
||||||
|
0 [swap [dup ++] direco] . cons
|
||||||
|
[0 swap [dup ++] direco] .
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('0 [dup ++] G x')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 0 [dup ++] G x
|
||||||
|
0 . [dup ++] G x
|
||||||
|
0 [dup ++] . G x
|
||||||
|
0 [dup ++] . [direco] cons [swap] swoncat cons x
|
||||||
|
0 [dup ++] [direco] . cons [swap] swoncat cons x
|
||||||
|
0 [[dup ++] direco] . [swap] swoncat cons x
|
||||||
|
0 [[dup ++] direco] [swap] . swoncat cons x
|
||||||
|
0 [[dup ++] direco] [swap] . swap concat cons x
|
||||||
|
0 [swap] [[dup ++] direco] . concat cons x
|
||||||
|
0 [swap [dup ++] direco] . cons x
|
||||||
|
[0 swap [dup ++] direco] . x
|
||||||
|
[0 swap [dup ++] direco] . 0 swap [dup ++] direco
|
||||||
|
[0 swap [dup ++] direco] 0 . swap [dup ++] direco
|
||||||
|
0 [0 swap [dup ++] direco] . [dup ++] direco
|
||||||
|
0 [0 swap [dup ++] direco] [dup ++] . direco
|
||||||
|
0 [0 swap [dup ++] direco] [dup ++] . dip rest cons
|
||||||
|
0 . dup ++ [0 swap [dup ++] direco] rest cons
|
||||||
|
0 0 . ++ [0 swap [dup ++] direco] rest cons
|
||||||
|
0 1 . [0 swap [dup ++] direco] rest cons
|
||||||
|
0 1 [0 swap [dup ++] direco] . rest cons
|
||||||
|
0 1 [swap [dup ++] direco] . cons
|
||||||
|
0 [1 swap [dup ++] direco] .
|
||||||
|
|
||||||
|
|
||||||
|
### Powers of 2
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('1 [dup 1 <<] G x x x x x x x x x')
|
||||||
|
```
|
||||||
|
|
||||||
|
1 2 4 8 16 32 64 128 256 [512 swap [dup 1 <<] direco]
|
||||||
|
|
||||||
|
|
||||||
|
# `n [x] times`
|
||||||
|
If we have one of these quoted programs we can drive it using `times` with the `x` combinator.
|
||||||
|
|
||||||
|
Let's define a word `n_range` that takes a starting integer and a count and leaves that many consecutive integers on the stack. For example:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('23 [dup ++] G 5 [x] times pop')
|
||||||
|
```
|
||||||
|
|
||||||
|
23 24 25 26 27
|
||||||
|
|
||||||
|
|
||||||
|
We can use `dip` to untangle `[dup ++] G` from the arguments.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('23 5 [[dup ++] G] dip [x] times pop')
|
||||||
|
```
|
||||||
|
|
||||||
|
23 24 25 26 27
|
||||||
|
|
||||||
|
|
||||||
|
Now that the givens (arguments) are on the left we have the definition we're looking for:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('n_range == [[dup ++] G] dip [x] times pop')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('450 10 n_range')
|
||||||
|
```
|
||||||
|
|
||||||
|
450 451 452 453 454 455 456 457 458 459
|
||||||
|
|
||||||
|
|
||||||
|
This is better just using the `times` combinator though...
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('450 9 [dup ++] times')
|
||||||
|
```
|
||||||
|
|
||||||
|
450 451 452 453 454 455 456 457 458 459
|
||||||
|
|
||||||
|
|
||||||
|
# Generating Multiples of Three and Five
|
||||||
|
Look at the treatment of the Project Euler Problem One in [Developing a Program.ipynb](./Developing a Program.ipynb) and you'll see that we might be interested in generating an endless cycle of:
|
||||||
|
|
||||||
|
3 2 1 3 1 2 3
|
||||||
|
|
||||||
|
To do this we want to encode the numbers as pairs of bits in a single int:
|
||||||
|
|
||||||
|
3 2 1 3 1 2 3
|
||||||
|
0b 11 10 01 11 01 10 11 == 14811
|
||||||
|
|
||||||
|
And pick them off by masking with 3 (binary 11) and then shifting the int right two bits.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('PE1.1 == dup [3 &] dip 2 >>')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('14811 PE1.1')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 14811 PE1.1
|
||||||
|
14811 . PE1.1
|
||||||
|
14811 . dup [3 &] dip 2 >>
|
||||||
|
14811 14811 . [3 &] dip 2 >>
|
||||||
|
14811 14811 [3 &] . dip 2 >>
|
||||||
|
14811 . 3 & 14811 2 >>
|
||||||
|
14811 3 . & 14811 2 >>
|
||||||
|
3 . 14811 2 >>
|
||||||
|
3 14811 . 2 >>
|
||||||
|
3 14811 2 . >>
|
||||||
|
3 3702 .
|
||||||
|
|
||||||
|
|
||||||
|
If we plug `14811` and `[PE1.1]` into our generator form...
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('14811 [PE1.1] G')
|
||||||
|
```
|
||||||
|
|
||||||
|
[14811 swap [PE1.1] direco]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[14811 swap [PE1.1] direco] x')
|
||||||
|
```
|
||||||
|
|
||||||
|
3 [3702 swap [PE1.1] direco]
|
||||||
|
|
||||||
|
|
||||||
|
...we get a generator that works for seven cycles before it reaches zero:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[14811 swap [PE1.1] direco] 7 [x] times')
|
||||||
|
```
|
||||||
|
|
||||||
|
3 2 1 3 1 2 3 [0 swap [PE1.1] direco]
|
||||||
|
|
||||||
|
|
||||||
|
### Reset at Zero
|
||||||
|
We need a function that checks if the int has reached zero and resets it if so.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('PE1.1.check == dup [pop 14811] [] branch')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
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]
|
||||||
|
|
||||||
|
|
||||||
|
### Run 466 times
|
||||||
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('7 66 * 4 +')
|
||||||
|
```
|
||||||
|
|
||||||
|
466
|
||||||
|
|
||||||
|
|
||||||
|
If we drive our generator 466 times and sum the stack we get 999.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[14811 swap [PE1.1.check PE1.1] dip rest cons] 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] dip rest cons]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[14811 swap [PE1.1.check PE1.1] dip rest cons] 466 [x] times pop enstacken sum')
|
||||||
|
```
|
||||||
|
|
||||||
|
999
|
||||||
|
|
||||||
|
|
||||||
|
# Project Euler Problem One
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('PE1.2 == + dup [+] dip')
|
||||||
|
```
|
||||||
|
|
||||||
|
Now we can add `PE1.2` to the quoted program given to `times`.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('0 0 [0 swap [PE1.1.check PE1.1] direco] 466 [x [PE1.2] dip] times popop')
|
||||||
|
```
|
||||||
|
|
||||||
|
233168
|
||||||
|
|
||||||
|
|
||||||
|
Or using `G` we can write:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('0 0 0 [PE1.1.check PE1.1] G 466 [x [PE1.2] dip] times popop')
|
||||||
|
```
|
||||||
|
|
||||||
|
233168
|
||||||
|
|
||||||
|
|
||||||
|
# A generator for the Fibonacci Sequence.
|
||||||
|
Consider:
|
||||||
|
|
||||||
|
[b a F] x
|
||||||
|
[b a F] b a F
|
||||||
|
|
||||||
|
The obvious first thing to do is just add `b` and `a`:
|
||||||
|
|
||||||
|
[b a F] b a +
|
||||||
|
[b a F] b+a
|
||||||
|
|
||||||
|
From here we want to arrive at:
|
||||||
|
|
||||||
|
b [b+a b F]
|
||||||
|
|
||||||
|
Let's start with `swons`:
|
||||||
|
|
||||||
|
[b a F] b+a swons
|
||||||
|
[b+a b a F]
|
||||||
|
|
||||||
|
Considering this quote as a stack:
|
||||||
|
|
||||||
|
F a b b+a
|
||||||
|
|
||||||
|
We want to get it to:
|
||||||
|
|
||||||
|
F b b+a b
|
||||||
|
|
||||||
|
So:
|
||||||
|
|
||||||
|
F a b b+a popdd over
|
||||||
|
F b b+a b
|
||||||
|
|
||||||
|
And therefore:
|
||||||
|
|
||||||
|
[b+a b a F] [popdd over] infra
|
||||||
|
[b b+a b F]
|
||||||
|
|
||||||
|
And lastly:
|
||||||
|
|
||||||
|
[b b+a b F] uncons
|
||||||
|
b [b+a b F]
|
||||||
|
|
||||||
|
Done.
|
||||||
|
|
||||||
|
Putting it all together:
|
||||||
|
|
||||||
|
F == + swons [popdd over] infra uncons
|
||||||
|
|
||||||
|
And:
|
||||||
|
|
||||||
|
fib_gen == [1 1 F]
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('fib == + swons [popdd over] infra uncons')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('fib_gen == [1 1 fib]')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('fib_gen 10 [x] times')
|
||||||
|
```
|
||||||
|
|
||||||
|
1 2 3 5 8 13 21 34 55 89 [144 89 fib]
|
||||||
|
|
||||||
|
|
||||||
|
### Project Euler Problem Two
|
||||||
|
By considering the terms in the Fibonacci sequence whose values do 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 `pop`s it otherwise.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('PE2.1 == dup 2 % [+] [pop] branch')
|
||||||
|
```
|
||||||
|
|
||||||
|
And a predicate function that detects when the terms in the series "exceed four million".
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('PE2 == 0 fib_gen x [pop >4M] [popop] [[PE2.1] dip x] primrec')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('PE2')
|
||||||
|
```
|
||||||
|
|
||||||
|
4613732
|
||||||
|
|
||||||
|
|
||||||
|
Here's the collected program definitions:
|
||||||
|
|
||||||
|
fib == + swons [popdd over] infra uncons
|
||||||
|
fib_gen == [1 1 fib]
|
||||||
|
|
||||||
|
even == dup 2 %
|
||||||
|
>4M == 4000000 >
|
||||||
|
|
||||||
|
PE2.1 == even [+] [pop] branch
|
||||||
|
PE2 == 0 fib_gen x [pop >4M] [popop] [[PE2.1] dip x] primrec
|
||||||
|
|
||||||
|
### Even-valued Fibonacci Terms
|
||||||
|
|
||||||
|
Using `o` for odd and `e` for even:
|
||||||
|
|
||||||
|
o + o = e
|
||||||
|
e + e = e
|
||||||
|
o + e = o
|
||||||
|
|
||||||
|
So the Fibonacci sequence considered in terms of just parity would be:
|
||||||
|
|
||||||
|
o o e o o e o o e o o e o o e o o e
|
||||||
|
1 1 2 3 5 8 . . .
|
||||||
|
|
||||||
|
Every third term is even.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 0 fib] x x x [popop] dipd')
|
||||||
|
```
|
||||||
|
|
||||||
|
2 [3 2 fib]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('PE2.2 == x x x [popop] dipd')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 0 fib] 10 [PE2.2] times')
|
||||||
|
```
|
||||||
|
|
||||||
|
2 8 34 144 610 2584 10946 46368 196418 832040 [1346269 832040 fib]
|
||||||
|
|
||||||
|
|
||||||
|
Replace `x` with our new driver function `PE2.2` and start our `fib` generator at `1 0`.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('0 [1 0 fib] PE2.2 [pop >4M] [popop] [[PE2.1] dip PE2.2] primrec')
|
||||||
|
```
|
||||||
|
|
||||||
|
4613732
|
||||||
|
|
||||||
|
|
||||||
|
# How to compile these?
|
||||||
|
You would probably start with a special version of `G`, and perhaps modifications to the default `x`?
|
||||||
|
|
@ -0,0 +1,266 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# [Newton's method](https://en.wikipedia.org/wiki/Newton%27s_method)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from notebook_preamble import J, V, define"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Cf. [\"Why Functional Programming Matters\" by John Hughes](https://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"$a_{i+1} = \\frac{(a_i+\\frac{n}{a_i})}{2}$"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Let's define a function that computes the above equation:\n",
|
||||||
|
"\n",
|
||||||
|
" n a Q\n",
|
||||||
|
" ---------------\n",
|
||||||
|
" (a+n/a)/2\n",
|
||||||
|
"\n",
|
||||||
|
" n a tuck / + 2 /\n",
|
||||||
|
" a n a / + 2 /\n",
|
||||||
|
" a n/a + 2 /\n",
|
||||||
|
" a+n/a 2 /\n",
|
||||||
|
" (a+n/a)/2\n",
|
||||||
|
"\n",
|
||||||
|
"We want it to leave n but replace a, so we execute it with `unary`:\n",
|
||||||
|
"\n",
|
||||||
|
" Q == [tuck / + 2 /] unary"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('Q == [tuck / + 2 /] unary')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"And a function to compute the error:\n",
|
||||||
|
"\n",
|
||||||
|
" n a sqr - abs\n",
|
||||||
|
" |n-a**2|\n",
|
||||||
|
"\n",
|
||||||
|
"This should be `nullary` so as to leave both n and a on the stack below the error.\n",
|
||||||
|
"\n",
|
||||||
|
" err == [sqr - abs] nullary"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('err == [sqr - abs] nullary')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Now we can define a recursive program that expects a number `n`, an initial estimate `a`, and an epsilon value `ε`, and that leaves on the stack the square root of `n` to within the precision of the epsilon value. (Later on we'll refine it to generate the initial estimate and hard-code an epsilon value.)\n",
|
||||||
|
"\n",
|
||||||
|
" n a ε square-root\n",
|
||||||
|
" -----------------\n",
|
||||||
|
" √n\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"If we apply the two functions `Q` and `err` defined above we get the next approximation and the error on the stack below the epsilon.\n",
|
||||||
|
"\n",
|
||||||
|
" n a ε [Q err] dip\n",
|
||||||
|
" n a Q err ε \n",
|
||||||
|
" n a' err ε \n",
|
||||||
|
" n a' e ε\n",
|
||||||
|
"\n",
|
||||||
|
"Let's define the recursive function from here. Start with `ifte`; the predicate and the base case behavior are obvious:\n",
|
||||||
|
"\n",
|
||||||
|
" n a' e ε [<] [popop popd] [J] ifte\n",
|
||||||
|
"\n",
|
||||||
|
"Base-case\n",
|
||||||
|
"\n",
|
||||||
|
" n a' e ε popop popd\n",
|
||||||
|
" n a' popd\n",
|
||||||
|
" a'\n",
|
||||||
|
"\n",
|
||||||
|
"The recursive branch is pretty easy. Discard the error and recur.\n",
|
||||||
|
"\n",
|
||||||
|
" w/ K == [<] [popop popd] [J] ifte\n",
|
||||||
|
"\n",
|
||||||
|
" n a' e ε J\n",
|
||||||
|
" n a' e ε popd [Q err] dip [K] i\n",
|
||||||
|
" n a' ε [Q err] dip [K] i\n",
|
||||||
|
" n a' Q err ε [K] i\n",
|
||||||
|
" n a'' e ε K\n",
|
||||||
|
"\n",
|
||||||
|
"This fragment alone is pretty useful."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('K == [<] [popop popd] [popd [Q err] dip] primrec')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {
|
||||||
|
"scrolled": true
|
||||||
|
},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"5.000000232305737\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('25 10 0.001 dup K')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"5.000000000000005\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('25 10 0.000001 dup K')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"So now all we need is a way to generate an initial approximation and an epsilon value:\n",
|
||||||
|
"\n",
|
||||||
|
" square-root == dup 3 / 0.000001 dup K"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('square-root == dup 3 / 0.000001 dup K')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"6.000000000000007\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('36 square-root')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"2212475.6192184356\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('4895048365636 square-root')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"4895048365636.0"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"2212475.6192184356 * 2212475.6192184356"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 2",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python2"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 2
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython2",
|
||||||
|
"version": "2.7.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,140 @@
|
||||||
|
|
||||||
|
# [Newton's method](https://en.wikipedia.org/wiki/Newton%27s_method)
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from notebook_preamble import J, V, define
|
||||||
|
```
|
||||||
|
|
||||||
|
Cf. ["Why Functional Programming Matters" by John Hughes](https://www.cs.kent.ac.uk/people/staff/dat/miranda/whyfp90.pdf)
|
||||||
|
|
||||||
|
$a_{i+1} = \frac{(a_i+\frac{n}{a_i})}{2}$
|
||||||
|
|
||||||
|
Let's define a function that computes the above equation:
|
||||||
|
|
||||||
|
n a Q
|
||||||
|
---------------
|
||||||
|
(a+n/a)/2
|
||||||
|
|
||||||
|
n a tuck / + 2 /
|
||||||
|
a n a / + 2 /
|
||||||
|
a n/a + 2 /
|
||||||
|
a+n/a 2 /
|
||||||
|
(a+n/a)/2
|
||||||
|
|
||||||
|
We want it to leave n but replace a, so we execute it with `unary`:
|
||||||
|
|
||||||
|
Q == [tuck / + 2 /] unary
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('Q == [tuck / + 2 /] unary')
|
||||||
|
```
|
||||||
|
|
||||||
|
And a function to compute the error:
|
||||||
|
|
||||||
|
n a sqr - abs
|
||||||
|
|n-a**2|
|
||||||
|
|
||||||
|
This should be `nullary` so as to leave both n and a on the stack below the error.
|
||||||
|
|
||||||
|
err == [sqr - abs] nullary
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('err == [sqr - abs] nullary')
|
||||||
|
```
|
||||||
|
|
||||||
|
Now we can define a recursive program that expects a number `n`, an initial estimate `a`, and an epsilon value `ε`, and that leaves on the stack the square root of `n` to within the precision of the epsilon value. (Later on we'll refine it to generate the initial estimate and hard-code an epsilon value.)
|
||||||
|
|
||||||
|
n a ε square-root
|
||||||
|
-----------------
|
||||||
|
√n
|
||||||
|
|
||||||
|
|
||||||
|
If we apply the two functions `Q` and `err` defined above we get the next approximation and the error on the stack below the epsilon.
|
||||||
|
|
||||||
|
n a ε [Q err] dip
|
||||||
|
n a Q err ε
|
||||||
|
n a' err ε
|
||||||
|
n a' e ε
|
||||||
|
|
||||||
|
Let's define the recursive function from here. Start with `ifte`; the predicate and the base case behavior are obvious:
|
||||||
|
|
||||||
|
n a' e ε [<] [popop popd] [J] ifte
|
||||||
|
|
||||||
|
Base-case
|
||||||
|
|
||||||
|
n a' e ε popop popd
|
||||||
|
n a' popd
|
||||||
|
a'
|
||||||
|
|
||||||
|
The recursive branch is pretty easy. Discard the error and recur.
|
||||||
|
|
||||||
|
w/ K == [<] [popop popd] [J] ifte
|
||||||
|
|
||||||
|
n a' e ε J
|
||||||
|
n a' e ε popd [Q err] dip [K] i
|
||||||
|
n a' ε [Q err] dip [K] i
|
||||||
|
n a' Q err ε [K] i
|
||||||
|
n a'' e ε K
|
||||||
|
|
||||||
|
This fragment alone is pretty useful.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('K == [<] [popop popd] [popd [Q err] dip] primrec')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('25 10 0.001 dup K')
|
||||||
|
```
|
||||||
|
|
||||||
|
5.000000232305737
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('25 10 0.000001 dup K')
|
||||||
|
```
|
||||||
|
|
||||||
|
5.000000000000005
|
||||||
|
|
||||||
|
|
||||||
|
So now all we need is a way to generate an initial approximation and an epsilon value:
|
||||||
|
|
||||||
|
square-root == dup 3 / 0.000001 dup K
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('square-root == dup 3 / 0.000001 dup K')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('36 square-root')
|
||||||
|
```
|
||||||
|
|
||||||
|
6.000000000000007
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('4895048365636 square-root')
|
||||||
|
```
|
||||||
|
|
||||||
|
2212475.6192184356
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
2212475.6192184356 * 2212475.6192184356
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
4895048365636.0
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -0,0 +1,275 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# [Quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formula)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from notebook_preamble import J, V, define"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Cf. [jp-quadratic.html](http://www.kevinalbrecht.com/code/joy-mirror/jp-quadratic.html)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
" -b +/- sqrt(b^2 - 4 * a * c)\n",
|
||||||
|
" -----------------------------\n",
|
||||||
|
" 2 * a"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"$\\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}$"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Write a straightforward program with variable names.\n",
|
||||||
|
" b neg b sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2\n",
|
||||||
|
"\n",
|
||||||
|
"### Check it.\n",
|
||||||
|
"\n",
|
||||||
|
" b neg b sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2\n",
|
||||||
|
" -b b sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2\n",
|
||||||
|
" -b b^2 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2\n",
|
||||||
|
" -b b^2 4ac - sqrt [+] [-] cleave a 2 * [truediv] cons app2\n",
|
||||||
|
" -b b^2-4ac sqrt [+] [-] cleave a 2 * [truediv] cons app2\n",
|
||||||
|
" -b sqrt(b^2-4ac) [+] [-] cleave a 2 * [truediv] cons app2\n",
|
||||||
|
"\n",
|
||||||
|
" -b -b+sqrt(b^2-4ac) -b-sqrt(b^2-4ac) a 2 * [truediv] cons app2\n",
|
||||||
|
" -b -b+sqrt(b^2-4ac) -b-sqrt(b^2-4ac) 2a [truediv] cons app2\n",
|
||||||
|
" -b -b+sqrt(b^2-4ac) -b-sqrt(b^2-4ac) [2a truediv] app2\n",
|
||||||
|
" -b -b+sqrt(b^2-4ac)/2a -b-sqrt(b^2-4ac)/2a\n",
|
||||||
|
"### Codicil\n",
|
||||||
|
" -b -b+sqrt(b^2-4ac)/2a -b-sqrt(b^2-4ac)/2a roll< pop\n",
|
||||||
|
" -b+sqrt(b^2-4ac)/2a -b-sqrt(b^2-4ac)/2a -b pop\n",
|
||||||
|
" -b+sqrt(b^2-4ac)/2a -b-sqrt(b^2-4ac)/2a"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Derive a definition.\n",
|
||||||
|
"\n",
|
||||||
|
" b neg b sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2 roll< pop\n",
|
||||||
|
" b [neg] dupdip sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2 roll< pop\n",
|
||||||
|
" b a c [[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2 roll< pop\n",
|
||||||
|
" b a c a [[[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave] dip 2 * [truediv] cons app2 roll< pop\n",
|
||||||
|
" b a c over [[[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave] dip 2 * [truediv] cons app2 roll< pop"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('quadratic == over [[[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave] dip 2 * [truediv] cons app2 roll< pop')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"-0.3819660112501051 -2.618033988749895\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('3 1 1 quadratic')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Simplify\n",
|
||||||
|
"We can define a `pm` plus-or-minus function:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('pm == [+] [-] cleave popdd')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Then `quadratic` becomes:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('quadratic == over [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [truediv] cons app2')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"-0.3819660112501051 -2.618033988749895\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('3 1 1 quadratic')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Define a \"native\" `pm` function.\n",
|
||||||
|
"The definition of `pm` above is pretty elegant, but the implementation takes a lot of steps relative to what it's accomplishing. Since we are likely to use `pm` more than once in the future, let's write a primitive in Python and add it to the dictionary."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from joy.library import SimpleFunctionWrapper\n",
|
||||||
|
"from notebook_preamble import D\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"@SimpleFunctionWrapper\n",
|
||||||
|
"def pm(stack):\n",
|
||||||
|
" a, (b, stack) = stack\n",
|
||||||
|
" p, m, = b + a, b - a\n",
|
||||||
|
" return m, (p, stack)\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"D['pm'] = pm"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"The resulting trace is short enough to fit on a page."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . 3 1 1 quadratic\n",
|
||||||
|
" 3 . 1 1 quadratic\n",
|
||||||
|
" 3 1 . 1 quadratic\n",
|
||||||
|
" 3 1 1 . quadratic\n",
|
||||||
|
" 3 1 1 . over [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [truediv] cons app2\n",
|
||||||
|
" 3 1 1 1 . [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [truediv] cons app2\n",
|
||||||
|
" 3 1 1 1 [[[neg] dupdip sqr 4] dipd * * - sqrt pm] . dip 2 * [truediv] cons app2\n",
|
||||||
|
" 3 1 1 . [[neg] dupdip sqr 4] dipd * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" 3 1 1 [[neg] dupdip sqr 4] . dipd * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" 3 . [neg] dupdip sqr 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" 3 [neg] . dupdip sqr 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" 3 . neg 3 sqr 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -3 . 3 sqr 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -3 3 . sqr 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -3 3 . dup mul 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -3 3 3 . mul 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -3 9 . 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -3 9 4 . 1 1 * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -3 9 4 1 . 1 * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -3 9 4 1 1 . * * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -3 9 4 1 . * - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -3 9 4 . - sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -3 5 . sqrt pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -3 2.23606797749979 . pm 1 2 * [truediv] cons app2\n",
|
||||||
|
" -0.7639320225002102 -5.23606797749979 . 1 2 * [truediv] cons app2\n",
|
||||||
|
" -0.7639320225002102 -5.23606797749979 1 . 2 * [truediv] cons app2\n",
|
||||||
|
" -0.7639320225002102 -5.23606797749979 1 2 . * [truediv] cons app2\n",
|
||||||
|
" -0.7639320225002102 -5.23606797749979 2 . [truediv] cons app2\n",
|
||||||
|
" -0.7639320225002102 -5.23606797749979 2 [truediv] . cons app2\n",
|
||||||
|
" -0.7639320225002102 -5.23606797749979 [2 truediv] . app2\n",
|
||||||
|
" [-0.7639320225002102] [2 truediv] . infra first [-5.23606797749979] [2 truediv] infra first\n",
|
||||||
|
" -0.7639320225002102 . 2 truediv [] swaack first [-5.23606797749979] [2 truediv] infra first\n",
|
||||||
|
" -0.7639320225002102 2 . truediv [] swaack first [-5.23606797749979] [2 truediv] infra first\n",
|
||||||
|
" -0.3819660112501051 . [] swaack first [-5.23606797749979] [2 truediv] infra first\n",
|
||||||
|
" -0.3819660112501051 [] . swaack first [-5.23606797749979] [2 truediv] infra first\n",
|
||||||
|
" [-0.3819660112501051] . first [-5.23606797749979] [2 truediv] infra first\n",
|
||||||
|
" -0.3819660112501051 . [-5.23606797749979] [2 truediv] infra first\n",
|
||||||
|
" -0.3819660112501051 [-5.23606797749979] . [2 truediv] infra first\n",
|
||||||
|
"-0.3819660112501051 [-5.23606797749979] [2 truediv] . infra first\n",
|
||||||
|
" -5.23606797749979 . 2 truediv [-0.3819660112501051] swaack first\n",
|
||||||
|
" -5.23606797749979 2 . truediv [-0.3819660112501051] swaack first\n",
|
||||||
|
" -2.618033988749895 . [-0.3819660112501051] swaack first\n",
|
||||||
|
" -2.618033988749895 [-0.3819660112501051] . swaack first\n",
|
||||||
|
" -0.3819660112501051 [-2.618033988749895] . first\n",
|
||||||
|
" -0.3819660112501051 -2.618033988749895 . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('3 1 1 quadratic')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 2",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python2"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 2
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython2",
|
||||||
|
"version": "2.7.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,153 @@
|
||||||
|
|
||||||
|
# [Quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formula)
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from notebook_preamble import J, V, define
|
||||||
|
```
|
||||||
|
|
||||||
|
Cf. [jp-quadratic.html](http://www.kevinalbrecht.com/code/joy-mirror/jp-quadratic.html)
|
||||||
|
|
||||||
|
-b +/- sqrt(b^2 - 4 * a * c)
|
||||||
|
-----------------------------
|
||||||
|
2 * a
|
||||||
|
|
||||||
|
$\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$
|
||||||
|
|
||||||
|
# Write a straightforward program with variable names.
|
||||||
|
b neg b sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2
|
||||||
|
|
||||||
|
### Check it.
|
||||||
|
|
||||||
|
b neg b sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2
|
||||||
|
-b b sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2
|
||||||
|
-b b^2 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2
|
||||||
|
-b b^2 4ac - sqrt [+] [-] cleave a 2 * [truediv] cons app2
|
||||||
|
-b b^2-4ac sqrt [+] [-] cleave a 2 * [truediv] cons app2
|
||||||
|
-b sqrt(b^2-4ac) [+] [-] cleave a 2 * [truediv] cons app2
|
||||||
|
|
||||||
|
-b -b+sqrt(b^2-4ac) -b-sqrt(b^2-4ac) a 2 * [truediv] cons app2
|
||||||
|
-b -b+sqrt(b^2-4ac) -b-sqrt(b^2-4ac) 2a [truediv] cons app2
|
||||||
|
-b -b+sqrt(b^2-4ac) -b-sqrt(b^2-4ac) [2a truediv] app2
|
||||||
|
-b -b+sqrt(b^2-4ac)/2a -b-sqrt(b^2-4ac)/2a
|
||||||
|
### Codicil
|
||||||
|
-b -b+sqrt(b^2-4ac)/2a -b-sqrt(b^2-4ac)/2a roll< pop
|
||||||
|
-b+sqrt(b^2-4ac)/2a -b-sqrt(b^2-4ac)/2a -b pop
|
||||||
|
-b+sqrt(b^2-4ac)/2a -b-sqrt(b^2-4ac)/2a
|
||||||
|
|
||||||
|
# Derive a definition.
|
||||||
|
|
||||||
|
b neg b sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2 roll< pop
|
||||||
|
b [neg] dupdip sqr 4 a c * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2 roll< pop
|
||||||
|
b a c [[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave a 2 * [truediv] cons app2 roll< pop
|
||||||
|
b a c a [[[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave] dip 2 * [truediv] cons app2 roll< pop
|
||||||
|
b a c over [[[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave] dip 2 * [truediv] cons app2 roll< pop
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('quadratic == over [[[neg] dupdip sqr 4] dipd * * - sqrt [+] [-] cleave] dip 2 * [truediv] cons app2 roll< pop')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('3 1 1 quadratic')
|
||||||
|
```
|
||||||
|
|
||||||
|
-0.3819660112501051 -2.618033988749895
|
||||||
|
|
||||||
|
|
||||||
|
### Simplify
|
||||||
|
We can define a `pm` plus-or-minus function:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('pm == [+] [-] cleave popdd')
|
||||||
|
```
|
||||||
|
|
||||||
|
Then `quadratic` becomes:
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('quadratic == over [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [truediv] cons app2')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('3 1 1 quadratic')
|
||||||
|
```
|
||||||
|
|
||||||
|
-0.3819660112501051 -2.618033988749895
|
||||||
|
|
||||||
|
|
||||||
|
### Define a "native" `pm` function.
|
||||||
|
The definition of `pm` above is pretty elegant, but the implementation takes a lot of steps relative to what it's accomplishing. Since we are likely to use `pm` more than once in the future, let's write a primitive in Python and add it to the dictionary.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from joy.library import SimpleFunctionWrapper
|
||||||
|
from notebook_preamble import D
|
||||||
|
|
||||||
|
|
||||||
|
@SimpleFunctionWrapper
|
||||||
|
def pm(stack):
|
||||||
|
a, (b, stack) = stack
|
||||||
|
p, m, = b + a, b - a
|
||||||
|
return m, (p, stack)
|
||||||
|
|
||||||
|
|
||||||
|
D['pm'] = pm
|
||||||
|
```
|
||||||
|
|
||||||
|
The resulting trace is short enough to fit on a page.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('3 1 1 quadratic')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 3 1 1 quadratic
|
||||||
|
3 . 1 1 quadratic
|
||||||
|
3 1 . 1 quadratic
|
||||||
|
3 1 1 . quadratic
|
||||||
|
3 1 1 . over [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [truediv] cons app2
|
||||||
|
3 1 1 1 . [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [truediv] cons app2
|
||||||
|
3 1 1 1 [[[neg] dupdip sqr 4] dipd * * - sqrt pm] . dip 2 * [truediv] cons app2
|
||||||
|
3 1 1 . [[neg] dupdip sqr 4] dipd * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
3 1 1 [[neg] dupdip sqr 4] . dipd * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
3 . [neg] dupdip sqr 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
3 [neg] . dupdip sqr 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
3 . neg 3 sqr 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
-3 . 3 sqr 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
-3 3 . sqr 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
-3 3 . dup mul 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
-3 3 3 . mul 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
-3 9 . 4 1 1 * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
-3 9 4 . 1 1 * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
-3 9 4 1 . 1 * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
-3 9 4 1 1 . * * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
-3 9 4 1 . * - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
-3 9 4 . - sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
-3 5 . sqrt pm 1 2 * [truediv] cons app2
|
||||||
|
-3 2.23606797749979 . pm 1 2 * [truediv] cons app2
|
||||||
|
-0.7639320225002102 -5.23606797749979 . 1 2 * [truediv] cons app2
|
||||||
|
-0.7639320225002102 -5.23606797749979 1 . 2 * [truediv] cons app2
|
||||||
|
-0.7639320225002102 -5.23606797749979 1 2 . * [truediv] cons app2
|
||||||
|
-0.7639320225002102 -5.23606797749979 2 . [truediv] cons app2
|
||||||
|
-0.7639320225002102 -5.23606797749979 2 [truediv] . cons app2
|
||||||
|
-0.7639320225002102 -5.23606797749979 [2 truediv] . app2
|
||||||
|
[-0.7639320225002102] [2 truediv] . infra first [-5.23606797749979] [2 truediv] infra first
|
||||||
|
-0.7639320225002102 . 2 truediv [] swaack first [-5.23606797749979] [2 truediv] infra first
|
||||||
|
-0.7639320225002102 2 . truediv [] swaack first [-5.23606797749979] [2 truediv] infra first
|
||||||
|
-0.3819660112501051 . [] swaack first [-5.23606797749979] [2 truediv] infra first
|
||||||
|
-0.3819660112501051 [] . swaack first [-5.23606797749979] [2 truediv] infra first
|
||||||
|
[-0.3819660112501051] . first [-5.23606797749979] [2 truediv] infra first
|
||||||
|
-0.3819660112501051 . [-5.23606797749979] [2 truediv] infra first
|
||||||
|
-0.3819660112501051 [-5.23606797749979] . [2 truediv] infra first
|
||||||
|
-0.3819660112501051 [-5.23606797749979] [2 truediv] . infra first
|
||||||
|
-5.23606797749979 . 2 truediv [-0.3819660112501051] swaack first
|
||||||
|
-5.23606797749979 2 . truediv [-0.3819660112501051] swaack first
|
||||||
|
-2.618033988749895 . [-0.3819660112501051] swaack first
|
||||||
|
-2.618033988749895 [-0.3819660112501051] . swaack first
|
||||||
|
-0.3819660112501051 [-2.618033988749895] . first
|
||||||
|
-0.3819660112501051 -2.618033988749895 .
|
||||||
|
|
||||||
|
|
@ -0,0 +1,44 @@
|
||||||
|
# Some Jupyter Notebooks and other material.
|
||||||
|
|
||||||
|
All of the notebooks are also available as HTML and Markdown files (generated using nbconvert) so you can view them without running Jupyter.
|
||||||
|
|
||||||
|
In order to run the [Jupyter Notebooks](https://jupyter.org/index.html) you need Jupyter (obviously) and you should install `Joypy`. Here's an example using `virtualenv` from the `joypy/` directory:
|
||||||
|
|
||||||
|
virtualenv --system-site-packages <DIRNAME>
|
||||||
|
. ./<DIRNAME>/bin/activate
|
||||||
|
python ./setup.py install
|
||||||
|
|
||||||
|
Once that's done you should be able to start Jupyter Notebook server with, e.g.:
|
||||||
|
|
||||||
|
python -n notebook
|
||||||
|
|
||||||
|
This starts it using the `virtualenv` version of Python so `joy` will be available. Navigate to the `joypy/docs` directory and the notebooks should be able to import the `notebook_preamble.py` file.
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
- 1. Basic Use of Joy in a Notebook
|
||||||
|
- 2. Library Examples - Short examples of each word in the dictionary. Various formats.
|
||||||
|
- 3. Developing a Program - Working with the first problem from Project Euler, "Find the sum of all the multiples of 3 or 5 below 1000", several forms of the program are derived.
|
||||||
|
- 4. Replacing Functions in the Dictionary - Shows the basics of defining new "primitive" functions in Python or as definitions and adding them to the dictionary.
|
||||||
|
- Factorial Function and Paramorphisms - A basic pattern of recursive control-flow.
|
||||||
|
- Generator Programs - Using the x combinator to make generator programs which can be used to create unbounded streams of values.
|
||||||
|
- Hylo-, Ana-, Cata-morphisms - Some basic patterns of recursive control-flow structures.
|
||||||
|
- Quadratic - Not-so-annoying Quadratic Formula.
|
||||||
|
- Trees - Ordered Binary Trees in Joy and more recursion.
|
||||||
|
- Zipper - A preliminary examination of the idea of data-structure "zippers" for traversing datastructures.
|
||||||
|
- notebook_preamble.py - Imported into notebooks to simplify the preamble code.
|
||||||
|
- pe1.py pe1.txt - Set up and execute a Joy program for the first problem from Project Euler. The pe1.txt file is the trace. It's 2.8M uncompressed. Compressed with gzip it becomes just 0.12M.
|
||||||
|
- repl.py - Run this script to start a REPL. Useful for e.g. running Joy code in a debugger.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
One of the things that interests me about Joy is how programming becomes
|
||||||
|
less about writing code and more about sound reasoning about simple
|
||||||
|
(almost geometric) programs. Many of the notebooks in this collection
|
||||||
|
consist of several pages of discussion to arrive at a few lines of Joy
|
||||||
|
definitions. I think this is a good thing. This is "literate
|
||||||
|
programming". The "programs" resemble mathematical proofs. You aren't
|
||||||
|
implementing so much as deriving. The structure of Joy seems to force
|
||||||
|
you to think clearly about the task in a way that is reliable but
|
||||||
|
extremely flexible. It feels like a puzzle game, and the puzzles are
|
||||||
|
often simple, and the solutions build on each other.
|
||||||
|
|
@ -0,0 +1,501 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"This notebook is about using the \"zipper\" with joy datastructures. See the [Zipper wikipedia entry](https://en.wikipedia.org/wiki/Zipper_%28data_structure%29) or the original paper: [\"FUNCTIONAL PEARL The Zipper\" by Gérard Huet](https://www.st.cs.uni-saarland.de/edu/seminare/2005/advanced-fp/docs/huet-zipper.pdf)\n",
|
||||||
|
"\n",
|
||||||
|
"Given a datastructure on the stack we can navigate through it, modify it, and rebuild it using the \"zipper\" technique."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Preamble"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from notebook_preamble import J, V, define"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Trees\n",
|
||||||
|
"In Joypy there aren't any complex datastructures, just ints, floats, strings, Symbols (strings that are names of functions) and sequences (aka lists, aka quoted literals, aka aggregates, etc...), but we can build [trees](https://en.wikipedia.org/wiki/Tree_%28data_structure%29) out of sequences."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1 [2 [3 4 25 6] 7] 8]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 [2 [3 4 25 6] 7] 8]')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Zipper in Joy\n",
|
||||||
|
"Zippers work by keeping track of the current item, the already-seen items, and the yet-to-be seen items as you traverse a datastructure (the datastructure used to keep track of these items is the zipper.)\n",
|
||||||
|
"\n",
|
||||||
|
"In Joy we can do this with the following words:\n",
|
||||||
|
"\n",
|
||||||
|
" z-down == [] swap uncons swap\n",
|
||||||
|
" z-up == swons swap shunt\n",
|
||||||
|
" z-right == [swons] cons dip uncons swap\n",
|
||||||
|
" z-left == swons [uncons swap] dip swap\n",
|
||||||
|
"\n",
|
||||||
|
"Let's use them to change 25 into 625. The first time a word is used I 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."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('z-down == [] swap uncons swap')\n",
|
||||||
|
"define('z-up == swons swap shunt')\n",
|
||||||
|
"define('z-right == [swons] cons dip uncons swap')\n",
|
||||||
|
"define('z-left == swons [uncons swap] dip swap')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . [1 [2 [3 4 25 6] 7] 8] z-down\n",
|
||||||
|
" [1 [2 [3 4 25 6] 7] 8] . z-down\n",
|
||||||
|
" [1 [2 [3 4 25 6] 7] 8] . [] swap uncons swap\n",
|
||||||
|
"[1 [2 [3 4 25 6] 7] 8] [] . swap uncons swap\n",
|
||||||
|
"[] [1 [2 [3 4 25 6] 7] 8] . uncons swap\n",
|
||||||
|
"[] 1 [[2 [3 4 25 6] 7] 8] . swap\n",
|
||||||
|
"[] [[2 [3 4 25 6] 7] 8] 1 . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('[1 [2 [3 4 25 6] 7] 8] z-down')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . [] [[2 [3 4 25 6] 7] 8] 1 z-right\n",
|
||||||
|
" [] . [[2 [3 4 25 6] 7] 8] 1 z-right\n",
|
||||||
|
" [] [[2 [3 4 25 6] 7] 8] . 1 z-right\n",
|
||||||
|
" [] [[2 [3 4 25 6] 7] 8] 1 . z-right\n",
|
||||||
|
" [] [[2 [3 4 25 6] 7] 8] 1 . [swons] cons dip uncons swap\n",
|
||||||
|
"[] [[2 [3 4 25 6] 7] 8] 1 [swons] . cons dip uncons swap\n",
|
||||||
|
"[] [[2 [3 4 25 6] 7] 8] [1 swons] . dip uncons swap\n",
|
||||||
|
" [] . 1 swons [[2 [3 4 25 6] 7] 8] uncons swap\n",
|
||||||
|
" [] 1 . swons [[2 [3 4 25 6] 7] 8] uncons swap\n",
|
||||||
|
" [] 1 . swap cons [[2 [3 4 25 6] 7] 8] uncons swap\n",
|
||||||
|
" 1 [] . cons [[2 [3 4 25 6] 7] 8] uncons swap\n",
|
||||||
|
" [1] . [[2 [3 4 25 6] 7] 8] uncons swap\n",
|
||||||
|
" [1] [[2 [3 4 25 6] 7] 8] . uncons swap\n",
|
||||||
|
" [1] [2 [3 4 25 6] 7] [8] . swap\n",
|
||||||
|
" [1] [8] [2 [3 4 25 6] 7] . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('[] [[2 [3 4 25 6] 7] 8] 1 z-right')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1] [8] [] [[3 4 25 6] 7] 2\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1] [8] [2 [3 4 25 6] 7] z-down')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1] [8] [2] [7] [3 4 25 6]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1] [8] [] [[3 4 25 6] 7] 2 z-right')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1] [8] [2] [7] [] [4 25 6] 3\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1] [8] [2] [7] [3 4 25 6] z-down')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1] [8] [2] [7] [3] [25 6] 4\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1] [8] [2] [7] [] [4 25 6] 3 z-right')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1] [8] [2] [7] [4 3] [6] 25\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1] [8] [2] [7] [3] [25 6] 4 z-right')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1] [8] [2] [7] [4 3] [6] 625\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1] [8] [2] [7] [4 3] [6] 25 sqr')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 12,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . [1] [8] [2] [7] [4 3] [6] 625 z-up\n",
|
||||||
|
" [1] . [8] [2] [7] [4 3] [6] 625 z-up\n",
|
||||||
|
" [1] [8] . [2] [7] [4 3] [6] 625 z-up\n",
|
||||||
|
" [1] [8] [2] . [7] [4 3] [6] 625 z-up\n",
|
||||||
|
" [1] [8] [2] [7] . [4 3] [6] 625 z-up\n",
|
||||||
|
" [1] [8] [2] [7] [4 3] . [6] 625 z-up\n",
|
||||||
|
" [1] [8] [2] [7] [4 3] [6] . 625 z-up\n",
|
||||||
|
"[1] [8] [2] [7] [4 3] [6] 625 . z-up\n",
|
||||||
|
"[1] [8] [2] [7] [4 3] [6] 625 . swons swap shunt\n",
|
||||||
|
"[1] [8] [2] [7] [4 3] [6] 625 . swap cons swap shunt\n",
|
||||||
|
"[1] [8] [2] [7] [4 3] 625 [6] . cons swap shunt\n",
|
||||||
|
"[1] [8] [2] [7] [4 3] [625 6] . swap shunt\n",
|
||||||
|
"[1] [8] [2] [7] [625 6] [4 3] . shunt\n",
|
||||||
|
" [1] [8] [2] [7] [3 4 625 6] . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('[1] [8] [2] [7] [4 3] [6] 625 z-up')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 13,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1] [8] [2 [3 4 625 6] 7]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1] [8] [2] [7] [3 4 625 6] z-up')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 14,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1 [2 [3 4 625 6] 7] 8]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1] [8] [2 [3 4 625 6] 7] z-up')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## `dip` and `infra`\n",
|
||||||
|
"In Joy we have the `dip` and `infra` combinators which can \"target\" or \"address\" any particular item in a Joy tree structure."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 15,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . [1 [2 [3 4 25 6] 7] 8] [[[[[[sqr] dipd] infra] dip] infra] dip] infra\n",
|
||||||
|
" [1 [2 [3 4 25 6] 7] 8] . [[[[[[sqr] dipd] infra] dip] infra] dip] infra\n",
|
||||||
|
"[1 [2 [3 4 25 6] 7] 8] [[[[[[sqr] dipd] infra] dip] infra] dip] . infra\n",
|
||||||
|
" 8 [2 [3 4 25 6] 7] 1 . [[[[[sqr] dipd] infra] dip] infra] dip [] swaack\n",
|
||||||
|
" 8 [2 [3 4 25 6] 7] 1 [[[[[sqr] dipd] infra] dip] infra] . dip [] swaack\n",
|
||||||
|
" 8 [2 [3 4 25 6] 7] . [[[[sqr] dipd] infra] dip] infra 1 [] swaack\n",
|
||||||
|
" 8 [2 [3 4 25 6] 7] [[[[sqr] dipd] infra] dip] . infra 1 [] swaack\n",
|
||||||
|
" 7 [3 4 25 6] 2 . [[[sqr] dipd] infra] dip [8] swaack 1 [] swaack\n",
|
||||||
|
" 7 [3 4 25 6] 2 [[[sqr] dipd] infra] . dip [8] swaack 1 [] swaack\n",
|
||||||
|
" 7 [3 4 25 6] . [[sqr] dipd] infra 2 [8] swaack 1 [] swaack\n",
|
||||||
|
" 7 [3 4 25 6] [[sqr] dipd] . infra 2 [8] swaack 1 [] swaack\n",
|
||||||
|
" 6 25 4 3 . [sqr] dipd [7] swaack 2 [8] swaack 1 [] swaack\n",
|
||||||
|
" 6 25 4 3 [sqr] . dipd [7] swaack 2 [8] swaack 1 [] swaack\n",
|
||||||
|
" 6 25 . sqr 4 3 [7] swaack 2 [8] swaack 1 [] swaack\n",
|
||||||
|
" 6 25 . dup mul 4 3 [7] swaack 2 [8] swaack 1 [] swaack\n",
|
||||||
|
" 6 25 25 . mul 4 3 [7] swaack 2 [8] swaack 1 [] swaack\n",
|
||||||
|
" 6 625 . 4 3 [7] swaack 2 [8] swaack 1 [] swaack\n",
|
||||||
|
" 6 625 4 . 3 [7] swaack 2 [8] swaack 1 [] swaack\n",
|
||||||
|
" 6 625 4 3 . [7] swaack 2 [8] swaack 1 [] swaack\n",
|
||||||
|
" 6 625 4 3 [7] . swaack 2 [8] swaack 1 [] swaack\n",
|
||||||
|
" 7 [3 4 625 6] . 2 [8] swaack 1 [] swaack\n",
|
||||||
|
" 7 [3 4 625 6] 2 . [8] swaack 1 [] swaack\n",
|
||||||
|
" 7 [3 4 625 6] 2 [8] . swaack 1 [] swaack\n",
|
||||||
|
" 8 [2 [3 4 625 6] 7] . 1 [] swaack\n",
|
||||||
|
" 8 [2 [3 4 625 6] 7] 1 . [] swaack\n",
|
||||||
|
" 8 [2 [3 4 625 6] 7] 1 [] . swaack\n",
|
||||||
|
" [1 [2 [3 4 625 6] 7] 8] . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('[1 [2 [3 4 25 6] 7] 8] [[[[[[sqr] dipd] infra] dip] infra] dip] infra')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"If you read the trace carefully you'll see that about half of it is the `dip` and `infra` combinators de-quoting programs and \"digging\" into the subject datastructure. Instead of maintaining temporary results on the stack they are pushed into the pending expression (continuation). When `sqr` has run the rest of the pending expression rebuilds the datastructure.\n",
|
||||||
|
"\n",
|
||||||
|
"## `Z`\n",
|
||||||
|
"Imagine a function `Z` that accepts a sequence of `dip` and `infra` combinators, a quoted program `[Q]`, and a datastructure to work on. It would effectively execute the quoted program as if it had been embedded in a nested series of quoted programs, e.g.:\n",
|
||||||
|
"\n",
|
||||||
|
" [...] [Q] [dip dip infra dip infra dip infra] Z\n",
|
||||||
|
" -------------------------------------------------------------\n",
|
||||||
|
" [...] [[[[[[[Q] dip] dip] infra] dip] infra] dip] infra\n",
|
||||||
|
" \n",
|
||||||
|
"The `Z` function isn't hard to make."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 16,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"define('Z == [[] cons cons] step i')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Here it is in action in a simplified scenario."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 17,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
" . 1 [2 3 4] Z\n",
|
||||||
|
" 1 . [2 3 4] Z\n",
|
||||||
|
" 1 [2 3 4] . Z\n",
|
||||||
|
" 1 [2 3 4] . [[] cons cons] step i\n",
|
||||||
|
" 1 [2 3 4] [[] cons cons] . step i\n",
|
||||||
|
" 1 2 [[] cons cons] . i [3 4] [[] cons cons] step i\n",
|
||||||
|
" 1 2 . [] cons cons [3 4] [[] cons cons] step i\n",
|
||||||
|
" 1 2 [] . cons cons [3 4] [[] cons cons] step i\n",
|
||||||
|
" 1 [2] . cons [3 4] [[] cons cons] step i\n",
|
||||||
|
" [1 2] . [3 4] [[] cons cons] step i\n",
|
||||||
|
" [1 2] [3 4] . [[] cons cons] step i\n",
|
||||||
|
" [1 2] [3 4] [[] cons cons] . step i\n",
|
||||||
|
" [1 2] 3 [[] cons cons] . i [4] [[] cons cons] step i\n",
|
||||||
|
" [1 2] 3 . [] cons cons [4] [[] cons cons] step i\n",
|
||||||
|
" [1 2] 3 [] . cons cons [4] [[] cons cons] step i\n",
|
||||||
|
" [1 2] [3] . cons [4] [[] cons cons] step i\n",
|
||||||
|
" [[1 2] 3] . [4] [[] cons cons] step i\n",
|
||||||
|
" [[1 2] 3] [4] . [[] cons cons] step i\n",
|
||||||
|
"[[1 2] 3] [4] [[] cons cons] . step i\n",
|
||||||
|
" [[1 2] 3] 4 [[] cons cons] . i i\n",
|
||||||
|
" [[1 2] 3] 4 . [] cons cons i\n",
|
||||||
|
" [[1 2] 3] 4 [] . cons cons i\n",
|
||||||
|
" [[1 2] 3] [4] . cons i\n",
|
||||||
|
" [[[1 2] 3] 4] . i\n",
|
||||||
|
" . [[1 2] 3] 4\n",
|
||||||
|
" [[1 2] 3] . 4\n",
|
||||||
|
" [[1 2] 3] 4 . \n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"V('1 [2 3 4] Z')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"And here it is doing the main thing."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 18,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[1 [2 [3 4 625 6] 7] 8]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"J('[1 [2 [3 4 25 6] 7] 8] [sqr] [dip dip infra dip infra dip infra] Z')"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Addressing\n",
|
||||||
|
"Because we are only using two combinators we could replace the list with a string made from only two characters.\n",
|
||||||
|
"\n",
|
||||||
|
" [...] [Q] 'ddididi' Zstr\n",
|
||||||
|
" -------------------------------------------------------------\n",
|
||||||
|
" [...] [[[[[[[Q] dip] dip] infra] dip] infra] dip] infra\n",
|
||||||
|
"\n",
|
||||||
|
"The string can be considered a name or address for an item in the subject datastructure.\n",
|
||||||
|
"\n",
|
||||||
|
"## Determining the right \"path\" for an item in a tree.\n",
|
||||||
|
"It's easy to read off (in reverse) the right sequence of \"d\" and \"i\" from the subject datastructure:\n",
|
||||||
|
"\n",
|
||||||
|
" [ n [ n [ n n x ...\n",
|
||||||
|
" i d i d i d d Bingo!"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 19,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Python 2",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python2"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 2
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython2",
|
||||||
|
"version": "2.7.13"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,277 @@
|
||||||
|
|
||||||
|
This notebook is about using the "zipper" with joy datastructures. See the [Zipper wikipedia entry](https://en.wikipedia.org/wiki/Zipper_%28data_structure%29) or the original paper: ["FUNCTIONAL PEARL The Zipper" by Gérard Huet](https://www.st.cs.uni-saarland.de/edu/seminare/2005/advanced-fp/docs/huet-zipper.pdf)
|
||||||
|
|
||||||
|
Given a datastructure on the stack we can navigate through it, modify it, and rebuild it using the "zipper" technique.
|
||||||
|
|
||||||
|
### Preamble
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
from notebook_preamble import J, V, define
|
||||||
|
```
|
||||||
|
|
||||||
|
## Trees
|
||||||
|
In Joypy there aren't any complex datastructures, just ints, floats, strings, Symbols (strings that are names of functions) and sequences (aka lists, aka quoted literals, aka aggregates, etc...), but we can build [trees](https://en.wikipedia.org/wiki/Tree_%28data_structure%29) out of sequences.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1 [2 [3 4 25 6] 7] 8]')
|
||||||
|
```
|
||||||
|
|
||||||
|
[1 [2 [3 4 25 6] 7] 8]
|
||||||
|
|
||||||
|
|
||||||
|
## Zipper in Joy
|
||||||
|
Zippers work by keeping track of the current item, the already-seen items, and the yet-to-be seen items as you traverse a datastructure (the datastructure used to keep track of these items is the zipper.)
|
||||||
|
|
||||||
|
In Joy we can do this with the following words:
|
||||||
|
|
||||||
|
z-down == [] swap uncons swap
|
||||||
|
z-up == swons swap shunt
|
||||||
|
z-right == [swons] cons dip uncons swap
|
||||||
|
z-left == swons [uncons swap] dip swap
|
||||||
|
|
||||||
|
Let's use them to change 25 into 625. The first time a word is used I 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.
|
||||||
|
|
||||||
|
|
||||||
|
```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')
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('[1 [2 [3 4 25 6] 7] 8] z-down')
|
||||||
|
```
|
||||||
|
|
||||||
|
. [1 [2 [3 4 25 6] 7] 8] z-down
|
||||||
|
[1 [2 [3 4 25 6] 7] 8] . z-down
|
||||||
|
[1 [2 [3 4 25 6] 7] 8] . [] swap uncons swap
|
||||||
|
[1 [2 [3 4 25 6] 7] 8] [] . swap uncons swap
|
||||||
|
[] [1 [2 [3 4 25 6] 7] 8] . uncons swap
|
||||||
|
[] 1 [[2 [3 4 25 6] 7] 8] . swap
|
||||||
|
[] [[2 [3 4 25 6] 7] 8] 1 .
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('[] [[2 [3 4 25 6] 7] 8] 1 z-right')
|
||||||
|
```
|
||||||
|
|
||||||
|
. [] [[2 [3 4 25 6] 7] 8] 1 z-right
|
||||||
|
[] . [[2 [3 4 25 6] 7] 8] 1 z-right
|
||||||
|
[] [[2 [3 4 25 6] 7] 8] . 1 z-right
|
||||||
|
[] [[2 [3 4 25 6] 7] 8] 1 . z-right
|
||||||
|
[] [[2 [3 4 25 6] 7] 8] 1 . [swons] cons dip uncons swap
|
||||||
|
[] [[2 [3 4 25 6] 7] 8] 1 [swons] . cons dip uncons swap
|
||||||
|
[] [[2 [3 4 25 6] 7] 8] [1 swons] . dip uncons swap
|
||||||
|
[] . 1 swons [[2 [3 4 25 6] 7] 8] uncons swap
|
||||||
|
[] 1 . swons [[2 [3 4 25 6] 7] 8] uncons swap
|
||||||
|
[] 1 . swap cons [[2 [3 4 25 6] 7] 8] uncons swap
|
||||||
|
1 [] . cons [[2 [3 4 25 6] 7] 8] uncons swap
|
||||||
|
[1] . [[2 [3 4 25 6] 7] 8] uncons swap
|
||||||
|
[1] [[2 [3 4 25 6] 7] 8] . uncons swap
|
||||||
|
[1] [2 [3 4 25 6] 7] [8] . swap
|
||||||
|
[1] [8] [2 [3 4 25 6] 7] .
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1] [8] [2 [3 4 25 6] 7] z-down')
|
||||||
|
```
|
||||||
|
|
||||||
|
[1] [8] [] [[3 4 25 6] 7] 2
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1] [8] [] [[3 4 25 6] 7] 2 z-right')
|
||||||
|
```
|
||||||
|
|
||||||
|
[1] [8] [2] [7] [3 4 25 6]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1] [8] [2] [7] [3 4 25 6] z-down')
|
||||||
|
```
|
||||||
|
|
||||||
|
[1] [8] [2] [7] [] [4 25 6] 3
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1] [8] [2] [7] [] [4 25 6] 3 z-right')
|
||||||
|
```
|
||||||
|
|
||||||
|
[1] [8] [2] [7] [3] [25 6] 4
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1] [8] [2] [7] [3] [25 6] 4 z-right')
|
||||||
|
```
|
||||||
|
|
||||||
|
[1] [8] [2] [7] [4 3] [6] 25
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1] [8] [2] [7] [4 3] [6] 25 sqr')
|
||||||
|
```
|
||||||
|
|
||||||
|
[1] [8] [2] [7] [4 3] [6] 625
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('[1] [8] [2] [7] [4 3] [6] 625 z-up')
|
||||||
|
```
|
||||||
|
|
||||||
|
. [1] [8] [2] [7] [4 3] [6] 625 z-up
|
||||||
|
[1] . [8] [2] [7] [4 3] [6] 625 z-up
|
||||||
|
[1] [8] . [2] [7] [4 3] [6] 625 z-up
|
||||||
|
[1] [8] [2] . [7] [4 3] [6] 625 z-up
|
||||||
|
[1] [8] [2] [7] . [4 3] [6] 625 z-up
|
||||||
|
[1] [8] [2] [7] [4 3] . [6] 625 z-up
|
||||||
|
[1] [8] [2] [7] [4 3] [6] . 625 z-up
|
||||||
|
[1] [8] [2] [7] [4 3] [6] 625 . z-up
|
||||||
|
[1] [8] [2] [7] [4 3] [6] 625 . swons swap shunt
|
||||||
|
[1] [8] [2] [7] [4 3] [6] 625 . swap cons swap shunt
|
||||||
|
[1] [8] [2] [7] [4 3] 625 [6] . cons swap shunt
|
||||||
|
[1] [8] [2] [7] [4 3] [625 6] . swap shunt
|
||||||
|
[1] [8] [2] [7] [625 6] [4 3] . shunt
|
||||||
|
[1] [8] [2] [7] [3 4 625 6] .
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1] [8] [2] [7] [3 4 625 6] z-up')
|
||||||
|
```
|
||||||
|
|
||||||
|
[1] [8] [2 [3 4 625 6] 7]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
J('[1] [8] [2 [3 4 625 6] 7] z-up')
|
||||||
|
```
|
||||||
|
|
||||||
|
[1 [2 [3 4 625 6] 7] 8]
|
||||||
|
|
||||||
|
|
||||||
|
## `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.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
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
|
||||||
|
[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
|
||||||
|
8 [2 [3 4 25 6] 7] 1 . [[[[[sqr] dipd] infra] dip] infra] dip [] swaack
|
||||||
|
8 [2 [3 4 25 6] 7] 1 [[[[[sqr] dipd] infra] dip] infra] . dip [] swaack
|
||||||
|
8 [2 [3 4 25 6] 7] . [[[[sqr] dipd] infra] dip] infra 1 [] swaack
|
||||||
|
8 [2 [3 4 25 6] 7] [[[[sqr] dipd] infra] dip] . infra 1 [] swaack
|
||||||
|
7 [3 4 25 6] 2 . [[[sqr] dipd] infra] dip [8] swaack 1 [] swaack
|
||||||
|
7 [3 4 25 6] 2 [[[sqr] dipd] infra] . dip [8] swaack 1 [] swaack
|
||||||
|
7 [3 4 25 6] . [[sqr] dipd] infra 2 [8] swaack 1 [] swaack
|
||||||
|
7 [3 4 25 6] [[sqr] dipd] . infra 2 [8] swaack 1 [] swaack
|
||||||
|
6 25 4 3 . [sqr] dipd [7] swaack 2 [8] swaack 1 [] swaack
|
||||||
|
6 25 4 3 [sqr] . dipd [7] swaack 2 [8] swaack 1 [] swaack
|
||||||
|
6 25 . sqr 4 3 [7] swaack 2 [8] swaack 1 [] swaack
|
||||||
|
6 25 . dup mul 4 3 [7] swaack 2 [8] swaack 1 [] swaack
|
||||||
|
6 25 25 . mul 4 3 [7] swaack 2 [8] swaack 1 [] swaack
|
||||||
|
6 625 . 4 3 [7] swaack 2 [8] swaack 1 [] swaack
|
||||||
|
6 625 4 . 3 [7] swaack 2 [8] swaack 1 [] swaack
|
||||||
|
6 625 4 3 . [7] swaack 2 [8] swaack 1 [] swaack
|
||||||
|
6 625 4 3 [7] . swaack 2 [8] swaack 1 [] swaack
|
||||||
|
7 [3 4 625 6] . 2 [8] swaack 1 [] swaack
|
||||||
|
7 [3 4 625 6] 2 . [8] swaack 1 [] swaack
|
||||||
|
7 [3 4 625 6] 2 [8] . swaack 1 [] swaack
|
||||||
|
8 [2 [3 4 625 6] 7] . 1 [] swaack
|
||||||
|
8 [2 [3 4 625 6] 7] 1 . [] swaack
|
||||||
|
8 [2 [3 4 625 6] 7] 1 [] . swaack
|
||||||
|
[1 [2 [3 4 625 6] 7] 8] .
|
||||||
|
|
||||||
|
|
||||||
|
If you read the trace carefully you'll see that about half of it is the `dip` and `infra` combinators de-quoting programs and "digging" into the subject datastructure. Instead of maintaining temporary results on the stack they are pushed into the pending expression (continuation). When `sqr` has run the rest of the pending expression rebuilds the datastructure.
|
||||||
|
|
||||||
|
## `Z`
|
||||||
|
Imagine a function `Z` that accepts a sequence of `dip` and `infra` combinators, a quoted program `[Q]`, and a datastructure to work on. It would effectively execute the quoted program as if it had been embedded in a nested series of quoted programs, e.g.:
|
||||||
|
|
||||||
|
[...] [Q] [dip dip infra dip infra dip infra] Z
|
||||||
|
-------------------------------------------------------------
|
||||||
|
[...] [[[[[[[Q] dip] dip] infra] dip] infra] dip] infra
|
||||||
|
|
||||||
|
The `Z` function isn't hard to make.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
define('Z == [[] cons cons] step i')
|
||||||
|
```
|
||||||
|
|
||||||
|
Here it is in action in a simplified scenario.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
V('1 [2 3 4] Z')
|
||||||
|
```
|
||||||
|
|
||||||
|
. 1 [2 3 4] Z
|
||||||
|
1 . [2 3 4] Z
|
||||||
|
1 [2 3 4] . Z
|
||||||
|
1 [2 3 4] . [[] cons cons] step i
|
||||||
|
1 [2 3 4] [[] cons cons] . step i
|
||||||
|
1 2 [[] cons cons] . i [3 4] [[] cons cons] step i
|
||||||
|
1 2 . [] cons cons [3 4] [[] cons cons] step i
|
||||||
|
1 2 [] . cons cons [3 4] [[] cons cons] step i
|
||||||
|
1 [2] . cons [3 4] [[] cons cons] step i
|
||||||
|
[1 2] . [3 4] [[] cons cons] step i
|
||||||
|
[1 2] [3 4] . [[] cons cons] step i
|
||||||
|
[1 2] [3 4] [[] cons cons] . step i
|
||||||
|
[1 2] 3 [[] cons cons] . i [4] [[] cons cons] step i
|
||||||
|
[1 2] 3 . [] cons cons [4] [[] cons cons] step i
|
||||||
|
[1 2] 3 [] . cons cons [4] [[] cons cons] step i
|
||||||
|
[1 2] [3] . cons [4] [[] cons cons] step i
|
||||||
|
[[1 2] 3] . [4] [[] cons cons] step i
|
||||||
|
[[1 2] 3] [4] . [[] cons cons] step i
|
||||||
|
[[1 2] 3] [4] [[] cons cons] . step i
|
||||||
|
[[1 2] 3] 4 [[] cons cons] . i i
|
||||||
|
[[1 2] 3] 4 . [] cons cons i
|
||||||
|
[[1 2] 3] 4 [] . cons cons i
|
||||||
|
[[1 2] 3] [4] . cons i
|
||||||
|
[[[1 2] 3] 4] . i
|
||||||
|
. [[1 2] 3] 4
|
||||||
|
[[1 2] 3] . 4
|
||||||
|
[[1 2] 3] 4 .
|
||||||
|
|
||||||
|
|
||||||
|
And here it is doing the main thing.
|
||||||
|
|
||||||
|
|
||||||
|
```python
|
||||||
|
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]
|
||||||
|
|
||||||
|
|
||||||
|
## Addressing
|
||||||
|
Because we are only using two combinators we could replace the list with a string made from only two characters.
|
||||||
|
|
||||||
|
[...] [Q] 'ddididi' Zstr
|
||||||
|
-------------------------------------------------------------
|
||||||
|
[...] [[[[[[[Q] dip] dip] infra] dip] infra] dip] infra
|
||||||
|
|
||||||
|
The string can be considered a name or address for an item in the subject datastructure.
|
||||||
|
|
||||||
|
## Determining the right "path" for an item in a tree.
|
||||||
|
It's easy to read off (in reverse) the right sequence of "d" and "i" from the subject datastructure:
|
||||||
|
|
||||||
|
[ n [ n [ n n x ...
|
||||||
|
i d i d i d d Bingo!
|
||||||
|
|
@ -0,0 +1,159 @@
|
||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"3"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"1 2 +"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"9"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"sqr"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"clear"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[u'tommy' 23 [u'richard' 48 [] []] [u'jenny' 18 [] []]]"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"[\"tommy\" 23 [\"richard\" 48 [] []] [\"jenny\" 18 [] []]] "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[u'tommy' 23 [u'richard' 48 [] []] [u'jenny' 18 [] []]] [first]"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"[first]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[u'tommy' 23 [u'richard' 48 [] []] [u'jenny' 18 [] []]] [u'tommy' 23 [u'richard' 48 [] []] [u'jenny' 18 [] []]] [first]"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"[dup] dip"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[u'tommy' 23 [u'richard' 48 [] []] [u'jenny' 18 [] []]] [u'tommy' 23 [u'richard' 48 [] []] [u'jenny' 18 [] []]] [not] [pop] [[first] dupdip] [[rest rest] dip step]"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"[not] [pop] roll< [dupdip] cons [[rest rest] dip step]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[u'tommy' 23 [u'richard' 48 [] []] [u'jenny' 18 [] []]] u'tommy' u'richard' u'jenny'"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"genrec"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "Joypy",
|
||||||
|
"language": "",
|
||||||
|
"name": "joypy"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"file_extension": ".joy",
|
||||||
|
"mimetype": "text/plain",
|
||||||
|
"name": "Joy"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,50 @@
|
||||||
|
from ipykernel.kernelbase import Kernel
|
||||||
|
from joy.library import initialize
|
||||||
|
from joy.joy import run
|
||||||
|
from joy.utils.stack import stack_to_string
|
||||||
|
|
||||||
|
|
||||||
|
class JoyKernel(Kernel):
|
||||||
|
implementation = 'Joypy'
|
||||||
|
implementation_version = '1.0'
|
||||||
|
language = 'Joy'
|
||||||
|
language_version = '0.1'
|
||||||
|
language_info = {
|
||||||
|
'name': 'Joy',
|
||||||
|
'mimetype': 'text/plain',
|
||||||
|
'file_extension': '.joy',
|
||||||
|
}
|
||||||
|
banner = "Echo kernel - as useful as a parrot"
|
||||||
|
|
||||||
|
def __init__(self, *a, **b):
|
||||||
|
self.D = initialize()
|
||||||
|
self.S = ()
|
||||||
|
super(JoyKernel, self).__init__(*a, **b)
|
||||||
|
|
||||||
|
def do_execute(
|
||||||
|
self,
|
||||||
|
code,
|
||||||
|
silent,
|
||||||
|
store_history=True,
|
||||||
|
user_expressions=None,
|
||||||
|
allow_stdin=False,
|
||||||
|
):
|
||||||
|
self.S = run(code, self.S, self.D)[0]
|
||||||
|
if not silent:
|
||||||
|
stream_content = {
|
||||||
|
'name': 'stdout',
|
||||||
|
'text': stack_to_string(self.S),
|
||||||
|
}
|
||||||
|
self.send_response(self.iopub_socket, 'stream', stream_content)
|
||||||
|
|
||||||
|
return {'status': 'ok',
|
||||||
|
# The base class increments the execution count
|
||||||
|
'execution_count': self.execution_count,
|
||||||
|
'payload': [],
|
||||||
|
'user_expressions': {},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
from ipykernel.kernelapp import IPKernelApp
|
||||||
|
IPKernelApp.launch_instance(kernel_class=JoyKernel)
|
||||||
|
|
@ -0,0 +1,4 @@
|
||||||
|
{
|
||||||
|
"argv": ["python", "-m", "joy_kernel", "-f", "{connection_file}"],
|
||||||
|
"display_name": "Joypy"
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,48 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright © 2017 Simon Forman
|
||||||
|
#
|
||||||
|
# This file is part of Joypy
|
||||||
|
#
|
||||||
|
# Joypy 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.
|
||||||
|
#
|
||||||
|
# Joypy 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 Joypy. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
#
|
||||||
|
from traceback import print_exc, format_exc
|
||||||
|
from joy.joy import run
|
||||||
|
from joy.library import initialize, DefinitionWrapper
|
||||||
|
from joy.utils.stack import stack_to_string
|
||||||
|
from joy.utils.pretty_print import TracePrinter
|
||||||
|
|
||||||
|
|
||||||
|
D = initialize()
|
||||||
|
S = ()
|
||||||
|
|
||||||
|
|
||||||
|
def J(text, stack=S, dictionary=D):
|
||||||
|
print stack_to_string(run(text, stack, dictionary)[0])
|
||||||
|
|
||||||
|
|
||||||
|
def V(text, stack=S, dictionary=D):
|
||||||
|
tp = TracePrinter()
|
||||||
|
try:
|
||||||
|
run(text, stack, dictionary, tp.viewer)
|
||||||
|
except:
|
||||||
|
exc = format_exc()
|
||||||
|
tp.print_()
|
||||||
|
print '-' * 73
|
||||||
|
print exc
|
||||||
|
else:
|
||||||
|
tp.print_()
|
||||||
|
|
||||||
|
|
||||||
|
define = lambda text: DefinitionWrapper.add_def(text, D)
|
||||||
|
|
@ -0,0 +1,24 @@
|
||||||
|
from notebook_preamble import J, D, DefinitionWrapper, V
|
||||||
|
|
||||||
|
#J('[0 swap [dup [pop 14811] [] branch dup [3 &] dip 2 >>] dip rest cons] 466 [x] times pop enstacken sum')
|
||||||
|
|
||||||
|
|
||||||
|
DefinitionWrapper.add_definitions('''
|
||||||
|
|
||||||
|
direco == dip rest cons
|
||||||
|
G == [direco] cons [swap] swoncat cons
|
||||||
|
|
||||||
|
PE1.1 == dup [3 &] dip 2 >>
|
||||||
|
PE1.1.check == dup [pop 14811] [] branch
|
||||||
|
PE1.2 == + dup [+] dip
|
||||||
|
|
||||||
|
PE1 == 0 0 0 [PE1.1.check PE1.1] G 466 [x [PE1.2] dip] times popop
|
||||||
|
|
||||||
|
''', D)
|
||||||
|
|
||||||
|
V('PE1')
|
||||||
|
|
||||||
|
|
||||||
|
# If the cleave combinator is built-in then this should be faster:
|
||||||
|
#
|
||||||
|
# PE1.1 == [3 &] [2 >>] cleave
|
||||||
|
|
@ -0,0 +1,96 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright © 2014, 2015, 2017 Simon Forman
|
||||||
|
#
|
||||||
|
# This file is part of joy.py
|
||||||
|
#
|
||||||
|
# joy.py 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.
|
||||||
|
#
|
||||||
|
# joy.py 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 joy.py. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
#
|
||||||
|
from joy.library import initialize
|
||||||
|
from joy.joy import repl
|
||||||
|
from joy.library import DefinitionWrapper
|
||||||
|
|
||||||
|
|
||||||
|
D = initialize()
|
||||||
|
|
||||||
|
|
||||||
|
from joy.library import SimpleFunctionWrapper
|
||||||
|
from joy.utils.stack import list_to_stack
|
||||||
|
|
||||||
|
|
||||||
|
@SimpleFunctionWrapper
|
||||||
|
def incr_at(stack):
|
||||||
|
'''Given a index and a sequence of integers, increment the integer at the index.
|
||||||
|
|
||||||
|
E.g.:
|
||||||
|
|
||||||
|
3 [0 1 2 3 4 5] incr_at
|
||||||
|
-----------------------------
|
||||||
|
[0 1 2 4 4 5]
|
||||||
|
|
||||||
|
'''
|
||||||
|
sequence, (i, stack) = stack
|
||||||
|
mem = []
|
||||||
|
while i >= 0:
|
||||||
|
term, sequence = sequence
|
||||||
|
mem.append(term)
|
||||||
|
i -= 1
|
||||||
|
mem[-1] += 1
|
||||||
|
return list_to_stack(mem, sequence), stack
|
||||||
|
|
||||||
|
|
||||||
|
D['incr_at'] = incr_at
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
DefinitionWrapper.add_definitions('''
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
TS0 == [not] swap unit [pop] swoncat
|
||||||
|
TS1 == [dip] cons [uncons] swoncat
|
||||||
|
treestep == swap [map] swoncat [TS1 [TS0] dip] dip genrec
|
||||||
|
|
||||||
|
Q == [tuck / + 2 /] unary
|
||||||
|
eps == [sqr - abs] nullary
|
||||||
|
K == [<] [popop swap pop] [popd [Q eps] dip] primrec
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
get_value == [roll< at] nullary
|
||||||
|
incr_value == [[popd incr_at] unary] dip
|
||||||
|
add_value == [+] cons dipd
|
||||||
|
incr_step_count == [++] dip
|
||||||
|
|
||||||
|
F == [popop 5 >=] [roll< popop] [get_value incr_value add_value incr_step_count] primrec
|
||||||
|
|
||||||
|
G == [first % not] [first /] [rest [not] [popop 0]] [ifte] genrec
|
||||||
|
|
||||||
|
''', D)
|
||||||
|
|
||||||
|
|
||||||
|
print '''\
|
||||||
|
Joypy - Copyright © 2017 Simon Forman
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type "warranty".
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type "sharing" for details.
|
||||||
|
Type "words" to see a list of all words, and "[<name>] help" to print the
|
||||||
|
docs for a word.
|
||||||
|
'''
|
||||||
|
stack = repl(dictionary=D)
|
||||||
|
|
||||||
|
|
@ -0,0 +1,31 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright © 2014, 2015, 2017 Simon Forman
|
||||||
|
#
|
||||||
|
# This file is part of joy.py
|
||||||
|
#
|
||||||
|
# joy.py 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.
|
||||||
|
#
|
||||||
|
# joy.py 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 joy.py. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
#
|
||||||
|
from .library import initialize
|
||||||
|
from .joy import repl
|
||||||
|
|
||||||
|
print '''\
|
||||||
|
Joypy - Copyright © 2017 Simon Forman
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type "warranty".
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type "sharing" for details.
|
||||||
|
Type "words" to see a list of all words, and "[<name>] help" to print the
|
||||||
|
docs for a word.
|
||||||
|
'''
|
||||||
|
stack = repl(dictionary=initialize())
|
||||||
|
|
@ -0,0 +1,121 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
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 Joypy.
|
||||||
|
|
||||||
|
Joypy 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.
|
||||||
|
|
||||||
|
Joypy 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 Joypy. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
|
||||||
|
§ 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=())
|
||||||
|
|
||||||
|
'''
|
||||||
|
from __future__ import print_function
|
||||||
|
try:
|
||||||
|
input = raw_input
|
||||||
|
except NameError:
|
||||||
|
pass
|
||||||
|
from traceback import print_exc, format_exc
|
||||||
|
from .parser import text_to_expression, ParseError, Symbol
|
||||||
|
from .utils.stack import stack_to_string
|
||||||
|
from .utils.pretty_print import TracePrinter
|
||||||
|
|
||||||
|
|
||||||
|
def joy(stack, expression, dictionary, viewer=None):
|
||||||
|
'''
|
||||||
|
Evaluate the Joy expression on the stack.
|
||||||
|
'''
|
||||||
|
while expression:
|
||||||
|
|
||||||
|
if viewer: viewer(stack, expression)
|
||||||
|
|
||||||
|
term, expression = expression
|
||||||
|
if isinstance(term, Symbol):
|
||||||
|
term = dictionary[term]
|
||||||
|
stack, expression, dictionary = term(stack, expression, dictionary)
|
||||||
|
else:
|
||||||
|
stack = term, stack
|
||||||
|
|
||||||
|
if viewer: viewer(stack, expression)
|
||||||
|
return stack, expression, dictionary
|
||||||
|
|
||||||
|
|
||||||
|
def run(text, stack, dictionary, viewer=None):
|
||||||
|
'''
|
||||||
|
Return the stack resulting from running the Joy code text on the stack.
|
||||||
|
'''
|
||||||
|
expression = text_to_expression(text)
|
||||||
|
return joy(stack, expression, dictionary, viewer)
|
||||||
|
|
||||||
|
|
||||||
|
def repl(stack=(), dictionary=None):
|
||||||
|
'''
|
||||||
|
Read-Evaluate-Print Loop
|
||||||
|
|
||||||
|
Accept input and run it on the stack, loop.
|
||||||
|
'''
|
||||||
|
if dictionary is None:
|
||||||
|
dictionary = {}
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
print()
|
||||||
|
print(stack_to_string(stack), '<-top')
|
||||||
|
print()
|
||||||
|
try:
|
||||||
|
text = input('joy? ')
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
break
|
||||||
|
viewer = TracePrinter()
|
||||||
|
try:
|
||||||
|
stack, _, dictionary = run(text, stack, dictionary, viewer.viewer)
|
||||||
|
except:
|
||||||
|
exc = format_exc() # Capture the exception.
|
||||||
|
viewer.print_() # Print the Joy trace.
|
||||||
|
print('-' * 73)
|
||||||
|
print(exc) # Print the original exception.
|
||||||
|
else:
|
||||||
|
viewer.print_()
|
||||||
|
except:
|
||||||
|
print_exc()
|
||||||
|
print()
|
||||||
|
return stack
|
||||||
|
|
@ -0,0 +1,110 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright © 2014, 2015, 2016, 2017 Simon Forman
|
||||||
|
#
|
||||||
|
# This file is part of Joypy.
|
||||||
|
#
|
||||||
|
# Joypy 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.
|
||||||
|
#
|
||||||
|
# Joypy 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 Joypy. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
#
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
§ Converting text to a joy expression.
|
||||||
|
|
||||||
|
This module exports a single function:
|
||||||
|
|
||||||
|
text_to_expression(text)
|
||||||
|
|
||||||
|
As well as a single Symbol class and a single Exception type:
|
||||||
|
|
||||||
|
ParseError
|
||||||
|
|
||||||
|
When supplied with a string this function returns a Python datastructure
|
||||||
|
that represents the Joy datastructure described by the text expression.
|
||||||
|
Any unbalanced square brackets will raise a ParseError.
|
||||||
|
'''
|
||||||
|
from re import Scanner
|
||||||
|
from .utils.stack import list_to_stack
|
||||||
|
|
||||||
|
|
||||||
|
class Symbol(str):
|
||||||
|
__repr__ = str.__str__
|
||||||
|
|
||||||
|
|
||||||
|
def text_to_expression(text):
|
||||||
|
'''
|
||||||
|
Convert a text to a Joy expression.
|
||||||
|
'''
|
||||||
|
return _parse(_tokenize(text))
|
||||||
|
|
||||||
|
|
||||||
|
class ParseError(ValueError): pass
|
||||||
|
|
||||||
|
|
||||||
|
def _tokenize(text):
|
||||||
|
'''
|
||||||
|
Convert a text into a stream of tokens, converting symbols using
|
||||||
|
symbol(token). Raise ValueError (with some of the failing text)
|
||||||
|
if the scan fails.
|
||||||
|
'''
|
||||||
|
tokens, rest = _scanner.scan(text)
|
||||||
|
if rest:
|
||||||
|
raise ParseError(
|
||||||
|
'Scan failed at position %i, %r'
|
||||||
|
% (len(text) - len(rest), rest[:10])
|
||||||
|
)
|
||||||
|
return tokens
|
||||||
|
|
||||||
|
|
||||||
|
def _parse(tokens):
|
||||||
|
'''
|
||||||
|
Return a stack/list expression of the tokens.
|
||||||
|
'''
|
||||||
|
frame = []
|
||||||
|
stack = []
|
||||||
|
for tok in tokens:
|
||||||
|
if tok == '[':
|
||||||
|
stack.append(frame)
|
||||||
|
frame = []
|
||||||
|
stack[-1].append(frame)
|
||||||
|
elif tok == ']':
|
||||||
|
try:
|
||||||
|
frame = stack.pop()
|
||||||
|
except IndexError:
|
||||||
|
raise ParseError('One or more extra closing brackets.')
|
||||||
|
frame[-1] = list_to_stack(frame[-1])
|
||||||
|
else:
|
||||||
|
frame.append(tok)
|
||||||
|
if stack:
|
||||||
|
raise ParseError('One or more unclosed brackets.')
|
||||||
|
return list_to_stack(frame)
|
||||||
|
|
||||||
|
|
||||||
|
def _scan_identifier(scanner, token): return Symbol(token)
|
||||||
|
def _scan_bracket(scanner, token): return token
|
||||||
|
def _scan_float(scanner, token): return float(token)
|
||||||
|
def _scan_int(scanner, token): return int(token)
|
||||||
|
def _scan_dstr(scanner, token): return token[1:-1].replace('\\"', '"')
|
||||||
|
def _scan_sstr(scanner, token): return token[1:-1].replace("\\'", "'")
|
||||||
|
|
||||||
|
|
||||||
|
_scanner = Scanner([
|
||||||
|
(r'-?\d+\.\d*', _scan_float),
|
||||||
|
(r'-?\d+', _scan_int),
|
||||||
|
(r'[•\w!@$%^&*()_+<>?|\/;:`~,.=-]+', _scan_identifier),
|
||||||
|
(r'\[|\]', _scan_bracket),
|
||||||
|
(r'"(?:[^"\\]|\\.)*"', _scan_dstr),
|
||||||
|
(r"'(?:[^'\\]|\\.)*'", _scan_sstr),
|
||||||
|
(r'\s+', None),
|
||||||
|
])
|
||||||
|
|
@ -0,0 +1,72 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright © 2016 Simon Forman
|
||||||
|
#
|
||||||
|
# This file is part of Joypy.
|
||||||
|
#
|
||||||
|
# Joypy 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.
|
||||||
|
#
|
||||||
|
# Joypy 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 Joypy. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
#
|
||||||
|
'''
|
||||||
|
Pretty printing support.
|
||||||
|
|
||||||
|
This is what does the formatting, e.g.:
|
||||||
|
|
||||||
|
. 23 18 mul 99 add
|
||||||
|
23 . 18 mul 99 add
|
||||||
|
23 18 . mul 99 add
|
||||||
|
414 . 99 add
|
||||||
|
414 99 . add
|
||||||
|
513 .
|
||||||
|
|
||||||
|
'''
|
||||||
|
# (Kinda clunky and hacky. This should be swapped out in favor of much
|
||||||
|
# smarter stuff.)
|
||||||
|
from __future__ import print_function
|
||||||
|
from traceback import print_exc
|
||||||
|
from .stack import expression_to_string, stack_to_string
|
||||||
|
|
||||||
|
|
||||||
|
class TracePrinter(object):
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.history = []
|
||||||
|
|
||||||
|
def viewer(self, stack, expression):
|
||||||
|
'''Pass this method as the viewer to joy() function.'''
|
||||||
|
self.history.append((stack, expression))
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return '\n'.join(self.go())
|
||||||
|
|
||||||
|
def go(self):
|
||||||
|
max_stack_length = 0
|
||||||
|
lines = []
|
||||||
|
for stack, expression in self.history:
|
||||||
|
stack = stack_to_string(stack)
|
||||||
|
expression = expression_to_string(expression)
|
||||||
|
n = len(stack)
|
||||||
|
if n > max_stack_length:
|
||||||
|
max_stack_length = n
|
||||||
|
lines.append((n, '%s . %s' % (stack, expression)))
|
||||||
|
return [ # Prefix spaces to line up '.'s.
|
||||||
|
(' ' * (max_stack_length - length) + line)
|
||||||
|
for length, line in lines
|
||||||
|
]
|
||||||
|
|
||||||
|
def print_(self):
|
||||||
|
try:
|
||||||
|
print(self)
|
||||||
|
except:
|
||||||
|
print_exc()
|
||||||
|
print('Exception while printing viewer.')
|
||||||
|
|
@ -0,0 +1,154 @@
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright © 2014, 2015, 2017 Simon Forman
|
||||||
|
#
|
||||||
|
# This file is part of joy.py
|
||||||
|
#
|
||||||
|
# joy.py 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.
|
||||||
|
#
|
||||||
|
# joy.py 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 joy.py. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
#
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
§ Stack
|
||||||
|
|
||||||
|
|
||||||
|
When talking about Joy we use the terms "stack", "list", "sequence" and
|
||||||
|
"aggregate" to mean the same thing: a simple datatype that 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
|
||||||
|
form of a stack with one or more items on it.
|
||||||
|
|
||||||
|
()
|
||||||
|
(1, ())
|
||||||
|
(2, (1, ()))
|
||||||
|
(3, (2, (1, ())))
|
||||||
|
...
|
||||||
|
|
||||||
|
And so on.
|
||||||
|
|
||||||
|
|
||||||
|
We have two very simple functions to build up a stack from a Python
|
||||||
|
iterable and also to iterate through a stack and yield its items
|
||||||
|
one-by-one in order, and two functions to generate string representations
|
||||||
|
of stacks:
|
||||||
|
|
||||||
|
list_to_stack()
|
||||||
|
|
||||||
|
iter_stack()
|
||||||
|
|
||||||
|
expression_to_string() (prints left-to-right)
|
||||||
|
|
||||||
|
stack_to_string() (prints right-to-left)
|
||||||
|
|
||||||
|
|
||||||
|
A word about the stack data structure.
|
||||||
|
|
||||||
|
Python has very nice "tuple packing and unpacking" in its syntax which
|
||||||
|
means we can directly "unpack" the expected arguments to a Joy function.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
def dup(stack):
|
||||||
|
head, tail = stack
|
||||||
|
return head, (head, tail)
|
||||||
|
|
||||||
|
We replace the argument "stack" by the expected structure of the stack,
|
||||||
|
in this case "(head, tail)", and Python takes care of de-structuring the
|
||||||
|
incoming argument and assigning values to the names. Note that Python
|
||||||
|
syntax doesn't require parentheses around tuples used in expressions
|
||||||
|
where they would be redundant.
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def list_to_stack(el, stack=()):
|
||||||
|
'''Convert a list (or other sequence) to a stack.
|
||||||
|
|
||||||
|
[1, 2, 3] -> (1, (2, (3, ())))
|
||||||
|
|
||||||
|
'''
|
||||||
|
for item in reversed(el):
|
||||||
|
stack = item, stack
|
||||||
|
return stack
|
||||||
|
|
||||||
|
|
||||||
|
def iter_stack(stack):
|
||||||
|
'''Iterate through the items on the stack.'''
|
||||||
|
while stack:
|
||||||
|
item, stack = stack
|
||||||
|
yield item
|
||||||
|
|
||||||
|
|
||||||
|
def stack_to_string(stack):
|
||||||
|
'''
|
||||||
|
Return a "pretty print" string for a stack.
|
||||||
|
|
||||||
|
The items are written right-to-left:
|
||||||
|
|
||||||
|
(top, (second, ...)) -> '... second top'
|
||||||
|
'''
|
||||||
|
f = lambda stack: reversed(list(iter_stack(stack)))
|
||||||
|
return _to_string(stack, f)
|
||||||
|
|
||||||
|
|
||||||
|
def expression_to_string(expression):
|
||||||
|
'''
|
||||||
|
Return a "pretty print" string for a expression.
|
||||||
|
|
||||||
|
The items are written left-to-right:
|
||||||
|
|
||||||
|
(top, (second, ...)) -> 'top second ...'
|
||||||
|
'''
|
||||||
|
return _to_string(expression, iter_stack)
|
||||||
|
|
||||||
|
|
||||||
|
def _to_string(stack, f):
|
||||||
|
if isinstance(stack, long): return str(stack).rstrip('L')
|
||||||
|
if not isinstance(stack, tuple): return repr(stack)
|
||||||
|
if not stack: return '' # shortcut
|
||||||
|
return ' '.join(map(_s, f(stack)))
|
||||||
|
|
||||||
|
|
||||||
|
_s = lambda s: (
|
||||||
|
'[%s]' % expression_to_string(s) if isinstance(s, tuple)
|
||||||
|
else str(s).rstrip('L') if isinstance(s, long)
|
||||||
|
else repr(s)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def pushback(quote, expression):
|
||||||
|
'''Concatinate quote onto expression.
|
||||||
|
|
||||||
|
In joy [1 2] [3 4] would become [1 2 3 4].
|
||||||
|
'''
|
||||||
|
return list_to_stack(list(iter_stack(quote)), expression)
|
||||||
|
|
||||||
|
|
||||||
|
def pick(s, n):
|
||||||
|
'''
|
||||||
|
Find the nth item on the stack. (Pick with zero is the same as "dup".)
|
||||||
|
'''
|
||||||
|
if n < 0:
|
||||||
|
raise ValueError
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
item, s = s
|
||||||
|
except ValueError:
|
||||||
|
raise IndexError
|
||||||
|
n -= 1
|
||||||
|
if n < 0:
|
||||||
|
break
|
||||||
|
return item
|
||||||
|
|
@ -0,0 +1,44 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
#
|
||||||
|
# Copyright © 2014, 2015, 2017 Simon Forman
|
||||||
|
#
|
||||||
|
# This file is part of joy.py
|
||||||
|
#
|
||||||
|
# joy.py 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.
|
||||||
|
#
|
||||||
|
# joy.py 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 joy.py. If not see <http://www.gnu.org/licenses/>.
|
||||||
|
#
|
||||||
|
from distutils.core import setup
|
||||||
|
from textwrap import dedent
|
||||||
|
|
||||||
|
|
||||||
|
setup(
|
||||||
|
name='Joypy',
|
||||||
|
version='0.1',
|
||||||
|
description='Python Implementation of Joy',
|
||||||
|
long_description=dedent('''\
|
||||||
|
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 written in C.'''),
|
||||||
|
author='Simon Forman',
|
||||||
|
author_email='forman.simon@gmail.com',
|
||||||
|
url='https://github.com/calroc/joypy',
|
||||||
|
packages=['joy', 'joy.utils'],
|
||||||
|
classifiers=[
|
||||||
|
'Development Status :: 3 - Alpha',
|
||||||
|
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
|
||||||
|
'Programming Language :: Python :: 2.7',
|
||||||
|
],
|
||||||
|
)
|
||||||