├── .github └── workflows │ └── rust.yml ├── .gitignore ├── 10-diff.png ├── 3-diff.png ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── README.md ├── src ├── a.rs ├── j.rs ├── p.rs ├── r.rs ├── s.rs └── x.rs ├── sums ├── README.md ├── sum.c ├── sum.j ├── sum.jl ├── sum.k ├── sum.r ├── sum.rs ├── sum.sh ├── sum2.rs └── sum3.rs └── tests └── t.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | on: 3 | push: 4 | branches: [ "main" ] 5 | pull_request: 6 | branches: [ "main" ] 7 | env: 8 | CARGO_TERM_COLOR: always 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v3 14 | - name: build 15 | run: cargo build --verbose --all-targets 16 | - name: tests 17 | run: cargo test --verbose 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | NOTES.md 3 | TODO.md 4 | **/a.out 5 | sums/sum 6 | sums/sum2 7 | sums/sum3 8 | -------------------------------------------------------------------------------- /10-diff.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cratelyn/j/214ec8df936b80f394758bd516dcbcf423f23a76/10-diff.png -------------------------------------------------------------------------------- /3-diff.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cratelyn/j/214ec8df936b80f394758bd516dcbcf423f23a76/3-diff.png -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "anyhow" 7 | version = "1.0.75" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "a4668cab20f66d8d020e1fbc0ebe47217433c1b6c8f2040faf858554e394ace6" 10 | 11 | [[package]] 12 | name = "j" 13 | version = "0.1.0" 14 | dependencies = [ 15 | "anyhow", 16 | ] 17 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "j" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | [lib] 7 | name = "j" 8 | path = "src/j.rs" 9 | 10 | [[bin]] 11 | name = "j" 12 | path = "src/x.rs" 13 | 14 | [dependencies] 15 | anyhow = "*" 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 💐 j 2 | 3 | j is a limited subset of J, an array programming language. this file is an accompanying essay. 4 | 5 | this project is, in spirit, a reimagining of the ["Incunabulum"][incunabulum] J interpreter 6 | fragment, implemented in Rust. this project is, in a sense, a work of speculative science-fiction, 7 | examining the linguistics of programming languages. 8 | 9 | ## ✨ technical overview 10 | 11 | the jsoftware wiki includes the following story concerning the original Incunabulum: 12 | 13 | > One summer weekend in 1989, Arthur Whitney visited Ken Iverson at Kiln Farm 14 | > and produced—on one page and in one afternoon—an interpreter fragment on the 15 | > AT&T 3B1 computer. 16 | 17 | accordingly, j does not intend to be a fully-fledged implementation of an array language. 18 | 19 | visit if you would like to learn more about J. the J wiki's 20 | ["Getting Started"][j-getting-started] page has useful information about installing J, and the 21 | ["NuVoc"][j-nuvoc] page is a useful reference for J's vocabulary. 22 | 23 | j values may be integers, arrays, or 2-dimensional matrices; higher-rank matrices are not 24 | implemented. a small number of verbs and adverbs are provided. variables may be defined. 25 | 26 | **monadic verbs** 27 | * `i.` "idot" generates a value 28 | * `|:` "transpose" rotates its argument 29 | * `#` "tally" counts the elements in its argument 30 | * `$` "shape" returns a value containing the dimensions of its argument 31 | * `[` "same" returns the given value 32 | * `]` "same" returns the given value 33 | * `>:` increments the given value 34 | 35 | **dyadic verbs** 36 | * `+` returns the sum of its two arguments 37 | * `*` returns the product of its two arguments 38 | * `[` "left" returns the left value 39 | * `]` "right" returns the right value 40 | 41 | **monadic adverbs** 42 | * `/` "insert" places a dyadic verb between items of its argument 43 | * `\` "prefix" returns successive prefixes of its argument 44 | 45 | **dyadic adverbs** 46 | * `/` "table" returns a table of entries using a dyadic verb and two arguments 47 | * `\` "infix" applies a verb to successive parts of its right-hand argument 48 | 49 | variables are assigned using `=:`. variable names may only contain lowercase ASCII `a-z` 50 | characters, numeric `0-9` characters, and `_` underscores. variable names must begin with a 51 | lowercase ASCII `a-z` character. 52 | 53 | #### 📂 project structure 54 | 55 | the code within this project is structured like so: 56 | 57 | ``` 58 | . 59 | ├── src 60 | │ ├── a.rs array 61 | │ ├── j.rs `j` library crate 62 | │ ├── p.rs prelude 63 | │ ├── r.rs lexing and parsing 64 | │ ├── s.rs symbol table 65 | │ └── x.rs interpreter binary 66 | └── tests 67 | └── t.rs test suite 68 | ``` 69 | 70 | # 📜 implementing j; an essay 71 | 72 | the rest of this document is an essay discussing the experience of writing software, using Rust, 73 | in a voice inspired by Arthur Whitney's style of C. 74 | 75 | ### 🌷 an introduction 76 | 77 | the purpose of building j was not merely to implement an array language in Rust. it was important 78 | to me that i did not write this software in the idiomatic style enforced by `cargo fmt`. 79 | conciseness should not come from retroactive search-and-replace, but from an honest attempt at 80 | adopting and recreating the _mindset_ of people who write software like this. 81 | 82 | in order to get a concrete sense of what this looks like, let's begin by reading a few snippets 83 | from the Incunabulum, an open-source implementation of k, and from j. 84 | 85 | #### 📜 the incunabulum 86 | 87 | conventional formatting of the Incunabulum's `main` function would look something like this: 88 | 89 | ```c 90 | int main() 91 | { 92 | char s[99]; 93 | Array a; 94 | while (gets(s)) 95 | { 96 | a = execute(parse(s)); 97 | print(a); 98 | } 99 | } 100 | ``` 101 | 102 | for C programmers, this should look like a familiar structure for the main event loop of an 103 | interpreter; we read an input, parse it, and then execute that statement. 104 | 105 | in the Incunabulum, Arthur Whitney wrote that loop in this single line: 106 | 107 | ```c 108 | main(){C s[99];while(gets(s))pr(ex(wd(s)));} 109 | ``` 110 | 111 | #### 🔬 ngn k 112 | 113 | ngn k is another commonly cited example of this style at its most extreme. excluding header 114 | imports and type aliases, its test runner fits in these 12 lines: 115 | 116 | ```c 117 | S C*mm(C*s,C**e)_(I f=open(s,0);ST stat h;fstat(f,&h);L n=h.st_size;C*r=mmap(0,n,1,2,f,0);cl(f);*e=r+n;r) 118 | S I nl(C*s,I n)_(C*p=s;I i=0;W(i ❗ **NB:** do not worry about understanding this snippet. 132 | 133 | i had always been fascinated by the fact that this is technically the same language as more 134 | orthodox dialiects of C, such as K&R, GNU, or BSD. 135 | 136 | j follows this spirit and style, in order to investigate whether "Whitney Rust" is possible, what 137 | it might teach us about Rust as a programming language, and to learn what writing software in this 138 | voice feels like, and why people do it. 139 | 140 | #### 🐣 j 141 | 142 | **🔁 main loop** 143 | 144 | above we looked at the Incunabulum's main event loop. here is j's equivalent entrypoint: 145 | 146 | ```rust 147 | mod p;use{p::*,j::*,std::io::Write}; 148 | fn main()->R<()>{let mut st=ST::default(); // define symbol table 149 | let prompt =| |{print!(" ");std::io::stdout().flush()?;ok!()}; // (callback) print whitespace 150 | let read =|_ |{let mut l=S::new();stdin().read_line(&mut l)?;Ok(l)}; // (callback) read input 151 | let mut eval=|s:S|{eval(&s,&mut st)}; // (callback) read and evaluate once 152 | let print =|a:A|{println!("{a}")}; // (callback) print array 153 | loop{prompt().and_then(read).and_then(&mut eval)?.map(print);}; /* !!! main event loop !!! */ } 154 | ``` 155 | 156 | **🏃 verbs** 157 | 158 | the core of the four dyadic verbs `[`, `]`, `+`, and `*` is shown below. the definitions of the `A` 159 | array type and the `D` dyadic verb enum are included for reference. 160 | 161 | ```rust 162 | pub enum D {Plus,Mul,Left,Right} 163 | pub struct A{/**columns*/ pub m:U, /**rows*/ pub n:U, 164 | /**data*/ d:*mut u8,/**layout*/l:L, 165 | /**memory state*/i:PD, } 166 | /**dyadic verbs*/impl D{ 167 | /*return dyad function**/ pub fn f(&self)->fn(I,I)->I{use D::*; 168 | match(self){Plus=>D::add, Mul=>D::mul, Left=>D::left, Right=>D::right} } 169 | /*add two numbers*/fn add (x:I,y:I)->I{x+y} /*multiply two numbers*/fn mul (x:I,y:I)->I{x*y} 170 | /*left */fn left(x:I,y:I)->I{x } /*right */fn right(x:I,y:I)->I{ y} 171 | } impl A{ 172 | pub fn d_left (self,r:A)->R{Ok(self) } 173 | pub fn d_right(self,r:A)->R{Ok(r) } 174 | pub fn d_plus(self,r:A) ->R{A::d_do(self,r,D::add)} 175 | pub fn d_mul (self,r:A) ->R{A::d_do(self,r,D::mul)} 176 | pub fn d_do(l@A{m:ml,n:nl,..}:A,r@A{m:mr,n:nr,..}:A,f:impl Fn(I,I)->I)->R>{ 177 | let(li,ri)=(l.as_i().ok(),r.as_i().ok());let(ls,rs)=(l.as_slice().ok(),r.as_slice().ok()); 178 | if let(Some(li),Some(ri))=(li,ri){r!(A::from_i(f(li,ri)))} // two scalars 179 | else if let(_,Some(s),None,a@A{m,n,..})|(a@A{m,n,..},None,Some(s),_)=(&l,li,ri,&r) // scalar and array 180 | {let(f)=|i,j|{Ok(f(a.get(i,j)?,s))};r!(A::new(*m,*n)?.init_with(f))} 181 | else if let(_,Some(s),None,a@A{m,n,..})|(a@A{m,n,..},None,Some(s),_)=(&l,ls,rs,&r) // slice and array 182 | {if(s.len()==*m){let(f)=|i,j|{let(x)=a.get(i,j)?;let(y)=(s[i-1]);Ok(f(x,y))};r!(A::new(*m,*n)?.init_with(f))}} 183 | else if (ml==mr)&&(nl==nr){let(m,n)=(ml,nl);r!(A::new(m,n)?.init_with( // matching arrays 184 | |i,j|{let(l,r)=(l.get(i,j)?,r.get(i,j)?);Ok(f(l,r))}))} 185 | else if (ml==nr)&&(nl==mr) /*NB: inherit the dimensions of the right-hand operand.*/ // rotation 186 | {let(f)=|i,j|{let(x)=l.get(j,i)?;let(y)=r.get(i,j)?;Ok(f(x,y))};r!(A::new(mr,nr)?.init_with(f))} 187 | bail!("length error"); 188 | } 189 | } 190 | ``` 191 | 192 | (_NB: we will talk more about the shorthand type aliases and macros in scope later in this essay_) 193 | 194 | ## 💭 on brevity; readability depends on who is reading 195 | 196 | thus, array programming languages are somewhat notorious for their terseness. this terseness often 197 | extends to the underlying implementation of these languages as well. before we continue any 198 | further, i'd like to cite a snippet from `@xpqz`'s excellent introduction to the K programming 199 | language: 200 | 201 | > K, like its Iversonian siblings APL and J, values conciseness, or perhaps we should say 202 | > terseness, of representation and speed of execution. 203 | > 204 | > [A]ccusations of “unreadable”, “write-only” and “impossible to learn” are leveled at all 205 | > Iversonian languages, k included. [..] **Readability is a property of the reader, not the 206 | > language.** 207 | 208 | - [_"Why k?"_][why-k] _(emphasis added)_ 209 | 210 | to restate this point bluntly, we will not spend time in this essay humoring questions about the 211 | aesthetic or practical validity of these languages. real people wake up, and solve real problems 212 | with array programming languages. whether this is the right paradigm for you is not dependent on 213 | your first impression, but upon what problems you are trying to solve, and whom you communicate 214 | with when solving them. 215 | 216 | ## 🌈 how broad is our imagination? 217 | 218 | programming languages used in industry today are descendents of a few shared ancestors, most 219 | commonly C. exceptions may draw from other languages such as ML, Lisp, Smalltalk, or Fortran, but 220 | even these all share some unspoken consensus regarding whitespace, loop indentation, symbol names, 221 | and the like. 222 | 223 | many readers approach array languages with some preconceptions of what code should look like. 224 | we as software engineers today have conservative ideas of what programming languages 225 | can look like, compared to the variety found in written languages around the world. 226 | 227 | ### ➰ compute a cumulative sum in imperative programming languages 228 | 229 | let's find the sum of integers `1..100` in a few programming languages. 230 | 231 | **note** source for these can all be found in the `sums/` directory of this repository. we will exclude 232 | unrelated syntactic overhead such as defining a `main` function, in order to focus on the core 233 | logic of computing this sum. 234 | 235 | **C** 236 | 237 | ```c 238 | int sum = 0; 239 | for (int i = 0; i <= 100; i++) 240 | { 241 | sum += i; 242 | } 243 | printf("%d", sum); 244 | ``` 245 | 246 | **POSIX Shell** 247 | 248 | ```sh 249 | SUM=0 250 | for i in $(seq 100); 251 | do 252 | SUM=$(expr $SUM + $i) 253 | done 254 | echo $SUM 255 | ``` 256 | 257 | **Julia** 258 | 259 | ```julia 260 | sum = 0 261 | for i=1:100 262 | global sum = sum + i 263 | end 264 | print(sum) 265 | ``` 266 | 267 | **Rust** 268 | 269 | ```rust 270 | let mut sum = 0; 271 | for i in 1..=100 { 272 | sum += i; 273 | } 274 | println!("{sum}"); 275 | ``` 276 | 277 | these are strikingly similar! consider that Julia appeared roughly 40 years after C, or that the 278 | Bourne shell is a command-line interpreter rather than a programming language. despite that, 279 | most of the differences between these examples are syntactic minutia: 280 | * in C, we must declare the type of the variable, an `int` 281 | * in a shell script, we must perform our arithmetic inside of a subshell, using the `expr` builtin 282 | * in Julia, we must specify that our assignment refers to the global `sum` variable 283 | * in C and Rust, loops are wrapped within `{` and `}` curly braces; in Julia and sh, `end` and 284 | `done` keywords are used. 285 | 286 | otherwise, all of these programs share a common backbone, expressed in the following pseudocode: 287 | 288 | ``` 289 | sum = 0 290 | for i in 1..100: 291 | sum += i 292 | print sum 293 | ``` 294 | 295 | #### λ find a cumulative sum in a functional language 296 | 297 | this exercise could be repeated with a collection of various functional languages, but a similar 298 | pattern can be found. programs declare a sequence or iterator and use a "fold" operation to find 299 | the sum. 300 | 301 | at its most explicit, this would look something like the following Rust program: 302 | 303 | ```rust 304 | fn main() { 305 | let sum = (1..=100).fold(0, std::ops::Add::add); 306 | println!("{sum}"); 307 | } 308 | ``` 309 | 310 | or, using the `Iterator::sum` helper: 311 | 312 | ```rust 313 | fn main() { 314 | let sum: u32 = (1..=100).sum(); 315 | println!("{sum}"); 316 | } 317 | ``` 318 | 319 | **⤆ a refresher on function composition: you are used to reading from right to left** 320 | 321 | suppose we have a value `x`, and two functions, `f(x)` and `g(x)`. "function composition" refers 322 | to the act of finding the resulting value when `g` is provided the output of `f(x)`. this may be 323 | written out as `g(f(x))`. 324 | 325 | this notation represents the precedence of functions such that you would read this expression 326 | from right to left. `x` is first provided to `f`, whose output is subsequently passed to `g`. 327 | 328 | mathemeticians alternately use the `∘` operator to represent this. this composition of `f` and 329 | `g` can also be written out as `f ∘ g`. some languages such as F# or Elixir provide a "pipeline" 330 | operator to facilitate this style, and other languages like Haskell may be written in "point-free" 331 | syntax such as this. Rust's `.` operator functions are similar sugar, passing its left-hand side 332 | as the first parameter to the associated method named in the right-hand side. 333 | 334 | functional languages' solutions to this problem will fit into one of two syntactic structures, 335 | shown in pseudo-code below: 336 | 337 | ``` 338 | sum(seq(100)) 339 | ``` 340 | 341 | ``` 342 | 100 |> seq |> sum 343 | ``` 344 | 345 | neither of these approaches are incorrect, but it is worth pointing out that many programmers are 346 | already quite familiar with the experience of reading expressions from right to left! additionally, 347 | many are also familiar with the idea of programming _tacitly,_ wherein variable names are not 348 | assigned to intermediate values (_the `i` in the for-loops above_). 349 | 350 | #### 󰘨 find a cumulative sum in an array language 351 | 352 | here are two solutions to the same problem in J, and its related cousin K. 353 | 354 | **K** 355 | 356 | ``` 357 | +/1+!100 358 | ``` 359 | 360 | **J** 361 | 362 | ``` 363 | +/1+i.100 364 | ``` 365 | 366 | _(NB: the "increment" operator is implemented later in this essay.)_ 367 | 368 | **🎳 breaking it down** 369 | 370 | the K solution performs this same computation in 8 characters. let's break down how this works 371 | bit-by-bit, starting with the lattermost 6 characters `1+!100`. 372 | 373 | here are the definitions for the `!` and `+` verbs, from the `kona` K interpreter's help pages: 374 | 375 | ``` 376 | ! monadic enumerate. !4 yields 0 1 2 3 377 | + dyadic plus. add numbers together 378 | ``` 379 | 380 | taken together, the expression `1+i.4` adds `1` to each element of the array `0 1 2 3`, yielding 381 | `1 2 3 4`. 382 | 383 | `/` is a kind of "adverb." in traditional human languages, an adverb is a part of speech used to 384 | apply an adjective to a verb. or in other words, it describes how a verb is/was performed. this 385 | same concept holds roughly true for J and K's adverbs. 386 | 387 | adverbs and [gerunds][j-gerunds] are very similar to higher-order functions. a higher-order 388 | function is a function that either accepts as an argument, or returns, another function. these 389 | constructs provide a way for programmers to abbreviate or abstract over common control flow 390 | patterns. J refers to the `/` adverb in this statement as "insert". 391 | 392 | the "insert" adverb places the provided dyadic (`+`) operator between the elements of its argument. 393 | thus, `+ / 1 2 3` is equivalent to `1+2+3`. notice that this is, syntax notwithstanding, the same 394 | idea as saying `fold()` 395 | 396 | so, the expression above has the following structure: 397 | 398 | ``` 399 | + / 1 + ! 100 400 | ┝┳┥ 401 | ┗━━━━━ the number 100 402 | ┝━┳━┥ 403 | ┗━━━━━━ the sequence of numbers 0 through 99 404 | ┝━━━┳━━━┥ 405 | ┗━━━━━━━━ the sequence of numbers 1 through 100 406 | ┝┳┥ 407 | ┗━━━━━━━━━━━━━━━ find the sum of the given argument 408 | ┝━━━┳━━━━━━━┥ 409 | ┗━━━━━━━━━━━━ add each of the numbers from 1 through 100 410 | ``` 411 | 412 | these programs share the same structure, save that `i.` is the verb for generating sequences, 413 | rather than K's `!`. importantly, we can see a shared syntactic lineage here. 414 | 415 | ###  language categories 416 | 417 | the united states government groups languages into categories from 1-5, ranking how difficult they 418 | are to learn. category 1 languages are considered "easy" to learn, while a category 5 language 419 | will take many hours before a student is considered fluent. 420 | 421 | there is a catch: this scale measures the perceived difficulty for _native English speakers_. 422 | 423 | the true difficulty of learning a new language is fundamentally entangled with what languages a 424 | student is previously familiar with. A Spanish speaker may be able to quickly learn Portuguese, 425 | but a language like Cantonese might include novel concepts such as semantically meaningful tone 426 | that would trip up such a student. in much the same way, J would be rather easy for a K programmer 427 | to learn and vice-versa. 428 | 429 | in truth, i think that the difficulty of learning array languages is overestimated. while this may 430 | seem to stem from incongruities in notation, i think this reputation is ultimately about larger 431 | differences in people's philosophies and preconceptions about human-computer interfaces. 432 | 433 | so, why _do_ so many programming languages look so similar? 434 | 435 | #### 🤨 "strangeness budget" 436 | 437 | we can find an illustrative story in the development of Rust's syntax for asynchrony. to briefly 438 | summarize, Rust opted to use "postfix" notation when awaiting a `Future`. this results in code 439 | that looks like: 440 | 441 | ```rust 442 | let bytes = client 443 | .send(request) 444 | .await 445 | .map(Response::into_body)?; 446 | ``` 447 | 448 | in other languages that use a traditional `await` keyword such as JavaScript, this might look 449 | something like: 450 | 451 | ```javascript 452 | let bytes = (await client.send(request)).into_body(); 453 | ``` 454 | 455 | many discussions about the validity of this approach have already been borne out at 456 | [great][rust-57640] [length][rust-50547]. i'll point to [this][ceej-postfix] excellent write-up 457 | about the benefits of postfix `await` if you are interested in reading further. suffice to say, 458 | this decision was controversial, because it strayed outside of what some people considered 459 | reasonable syntax for asynchrony. 460 | 461 | Steve Klabnik [wrote][klabnik-budget] about this phenomenon: 462 | 463 | > [I]t’s important to be considerate of how many things in your language will be strange for your 464 | > target audience, because if you put too many strange things in, they won’t give it a try. 465 | > 466 | > You can see us avoiding blowing the budget in Rust with many of our syntactic choices. We chose 467 | > to stick with curly braces, for example, because one of our major target audiences, systems 468 | > programmers, is currently using a curly brace language. Instead, we spend this strangeness 469 | > budget on our major, core feature: ownership and borrowing. 470 | 471 | in other words, in order to define and manage a strangeness budget, as with the idea of 472 | "categories" for human languages, you must identify who your prospective students are. as Steve 473 | noted, it was pragmatic and reasonable for Rust to focus on this demographic because many of its 474 | early adopters would be C or C++ programmers. 475 | 476 | our summing exercise above illustrated how similar different programming languages' looping 477 | constructs are. ultimately, each new programming language is incentivized _not_ to challenge 478 | people's notions of loops. 479 | 480 | Aaron Hsu has remarked in his [talks][hsu-apl] about APL that the people who have the most 481 | trouble learning languages like APL are often _computer science students_. we learn more than 482 | syntax or grammer when studying computer science: for better and for worse, we also internalize 483 | conventions of _thought._ 484 | 485 | readability is a property of the reader, indeed! 486 | 487 | ## 🍄 my experience 488 | 489 | so, you ask, how was it? 490 | 491 | hopefully at this point i've convinced you that this is an internally consistent programming 492 | paradigm, even if it does not seem like your personal cup of tea. i'll be honest, at the outset 493 | of this project it did not seem like my cup of tea either. 494 | 495 | after spending time building a piece of software in this style however, i grew to like it 496 | far more than i expected i would. in no particular order, let's gloss through some thoughts about 497 | this experience. 498 | 499 | ### 🌐 brevity amplifies local reasoning 500 | 501 | codebases for real-world production software are often quite large. most include tens of thousands 502 | lines of code, and it is not uncommon for this number to reach the hundreds of thousands, or even 503 | millions. 504 | 505 | **lexical sprawl introduces a high amount of non-local reasoning into our systems.** with that, 506 | we introduce a need for other specialized tooling: text editors with the ability to "fold" 507 | sections of text out of view, terminal multiplexers with tab and window management facilities, 508 | language servers to help find references to a given variable, formatting tools to maintain a 509 | consistent syntactic style, the list goes on. 510 | 511 | when working on j, i found that i spent about the same amount of time reading 512 | through my existing code to introduce a new feature, but reading became a passive activity. i 513 | no longer needed to scroll up and down, or jump to function definitions elsewhere. **my cognitive 514 | function was no longer divided between reading and traversal.** i could instead open a 515 | file, lean back, and read through the entirety of a subsystem without needing to manually interact 516 | further. 517 | 518 | in contrast, concise code has the effect of maximizing the amount of code that may be included in 519 | local reasoning. 520 | 521 | ### 🐘 sufficient brevity implies a DSL 522 | 523 | software written in this style includes a "_prelude_" of sorts, defining various shorthand forms. 524 | these preludes go beyond just type aliases like `typedef char C` or `typedef long I`, however. 525 | C's preprocessor is often leveraged to provide abstractions for keywords, function signatures, 526 | or even **control flow**. 527 | 528 | the Incunabulum's prelude is shown below. it defines an `R` shorthand for `return`ing a value, 529 | `DO` to perform an operation across the length of an array. 530 | 531 | ```c 532 | #define P printf 533 | #define R return 534 | #define V1(f) A f(w)A w; 535 | #define V2(f) A f(a,w)A a,w; 536 | #define DO(n,x) {I i=0,_n=(n);for(;i<_n;++i){x;}} 537 | ``` 538 | 539 | Kona, an open-source implementation of the k3 programming language, includes an almost verbatim 540 | copy of this same macro: 541 | 542 | ```c 543 | #define DO(n,x) {I i=0,_i=(n);for(;i<_i;++i){x;}} 544 | #define DO2(n,x){I j=0,_j=(n);for(;j<_j;++j){x;}} 545 | #define DO3(n,x){I k=0,_k=(n);for(;k<_k;++k){x;}} 546 | ``` 547 | 548 | as another example, Kona defines some control-flow macros for early returns, based on some predicate 549 | condition. 550 | 551 | ```c 552 | #define R return 553 | #define P(x,y) {if(x)R(y);} 554 | #define U(x) P(!(x),0) 555 | ``` 556 | 557 | shorthand for common control-flow like early returns is tremendously useful. Rust has the `?` 558 | operator for this very reason! the next snippet shows some ngn k's equivalent shorthand notation 559 | for loops, conditional statements, and switch statements. 560 | 561 | ```c 562 | #define W(x,a...) while(x){a;} 563 | #define B(x,a...) I(x,a;break) 564 | #define P(x,a...) I(x,_(a)) 565 | #define I(x,a...) if(x){a;} 566 | #define J(a...) else I(a) 567 | #define E(a...) else{a;} 568 | #define SW(x,a...) switch(x){a} 569 | ``` 570 | 571 | Rust was just as capable of defining such a prelude: `r!()` could be used to perform early 572 | returns, `b!()` could perform heap allocations, `R` served as a shorthand for a fallible 573 | operation resulting in `T`, and similar type aliases `C` or `I` were defined for characters and 574 | integers. 575 | 576 | j's prelude looks like this: 577 | 578 | ```rs 579 | //! prelude; shorthand aliases for common types and traits, macros for common patterns. 580 | pub(crate)use{Box as B,char as C,u32 as I,usize as U,Option as O,String as S,TryFrom as TF,TryInto as TI,Vec as V}; 581 | pub(crate)use{std::{alloc::Layout as L,clone::Clone as CL,cmp::{PartialEq as PE,PartialOrd as PO}, 582 | collections::{BTreeMap as BM,VecDeque as VD},fmt::{Debug as DBG,Display as DS,Formatter as FMT,Result as FR}, 583 | iter::{FromIterator as FI,IntoIterator as IIT,Iterator as IT},io::stdin, 584 | slice::{from_raw_parts,from_raw_parts_mut},str::FromStr as FS}}; 585 | pub(crate)use{anyhow::{Context,Error as E,anyhow as err,bail}}; 586 | #[macro_export] /**`return`*/ macro_rules! r {()=>{return};($e:expr)=>{return $e};} 587 | #[macro_export] /**`return Ok(Some(..))`*/ macro_rules! rro {($e:expr)=>{r!(Ok(Some($e)))}} 588 | #[macro_export] /**`Ok(())`*/ macro_rules! ok {()=>{Ok(())}} 589 | #[macro_export] /**`Box::new(..)`*/ macro_rules! b {($e:expr)=>{B::new($e)};} 590 | #[macro_export] /**`unreachable!()`*/ macro_rules! ur {()=>{unreachable!()}} 591 | /**`Result`*/ pub type R = Result; 592 | #[cfg(test)]/**test prelude*/pub(crate) mod tp{ 593 | pub(crate) use{assert_eq as eq,assert_ne as neq,assert as is}; 594 | } 595 | ``` 596 | 597 | in my practical experience, this was also a pleasant toolbox to maintain. "Don't Repeat Yourself" 598 | is an old adage among programmers, and this worked well to that effect. when i began to recognize 599 | a pattern of some sort, i could define a shorthand for it. 600 | 601 | LISP programmers have a mantra that code is data, and data is code; indeed, Kona's README notes 602 | that LISP was an important influence on the K language. along the same lines, this style puts a 603 | heavy emphasis on metaprogramming facilities. code is also syntax, and syntax is code. 604 | 605 | **brevity mandates the construction of a domain-specific language (DSL) in which a piece of 606 | software can then be written.** this style of hyper-succint code is ultimately a dialect to be 607 | embedded _within_ a "host" language. 608 | 609 | ### 🦀 brevity is not a mutually exclusive property 610 | 611 | writing concise Rust code did not detract from the traditional benefits of the language. 612 | 613 | rather than writing this as a 1:1 direct translation of the [Incunabulum][incunabulum], i was 614 | able to follow familiar idioms when implementing j, and found myself enjoying the usual benefits 615 | of writing software in Rust. 616 | 617 | **NB:** this next section assumes some previous familiarity with Rust's type system. 618 | 619 | **🌳 abstract syntax tree** 620 | 621 | as a straightforward example, this snippet of `src/r.rs` shows the definition of j's abstract 622 | syntax tree (AST). an AST is the structured representation of statements in a language, which 623 | most compilers and interpreters implement in some form or another. 624 | 625 | `SY` is a newtype wrapper around a `String`. they're tremendously useful. see 626 | ["New Type Idiom"][api-guidelines-newtype] in the Rust API guidelines for more information on this 627 | pattern. 628 | the `D` and `M` structures represent dyadic and monadic verbs: `+`, `*`, `i.`, and so forth. 629 | the `Yd` and `Ym` are structures are monadic and dyadic adverbs, `/` and `\`. 630 | 631 | `N` is a recursive structure that uses these to represent a statement in j. 632 | 633 | ```rust 634 | /**symbol */pub struct SY(S); 635 | /**dyadic verb */pub enum D {Plus,Mul, Left, Right } 636 | /**monadic verb */pub enum M {Idot,Shape,Tally,Transpose,Same,Inc} 637 | /**dyadic adverb */pub enum Yd{/**dyadic `/` */ Table , 638 | /**dyadic `\` */ Infix } 639 | /**monadic adverb */pub enum Ym{/**monadic `/`*/ Insert, 640 | /**monadic `\`*/ Prefix} 641 | /**ast node */pub enum N {/**array literal*/ A{a:A}, 642 | /**dyadic verb*/ D{d:D,l:B,r:B}, 643 | /**monadic verb*/ M{m:M,o:B}, 644 | /**dyadic adverb*/ Yd{yd:Yd,d:D,l:B,r:B}, 645 | /**monadic adverb*/ Ym{ym:Ym,d:D,o:B}, 646 | /**symbol*/ S{sy:SY}, 647 | /**symbol assignment*/E{sy:SY,e:B}} 648 | ``` 649 | 650 | while the monadic and dyadic verbs are simple enumerations, notice that the the `N` node contains 651 | heterogenous payloads for each variant. outlining the benefits of pattern matching and algebraic 652 | data types (ADTs) is out-of-scope for this essay, but in short: this approach helps prevent 653 | invalid fields from being accessed or written to. interacting with the `l` and `r` fields will 654 | cause a compilation failure, _unless_ we are within a block of code that has properly matched 655 | against an `A::N` value. 656 | 657 | **🔐 interfaces with guardrails** 658 | 659 | here are some abbreviated snippets of `src/a.rs`. first, we define a collection of "marker" 660 | types, to indicate whether the memory of an array has been initialized yet. this uses a "sealed" 661 | trait; see the [API Guidelines][api-guidelines-futureproof] for more information on this pattern. 662 | 663 | ```rust 664 | // src/a.rs 665 | /**sealed trait, memory markers*/pub trait MX{} impl MX for MU {} impl MX for MI {} 666 | /**marker: memory uninitialized*/#[derive(CL,DBG)]pub struct MU; 667 | /**marker: memory initialized*/ #[derive(CL,DBG)]pub struct MI; 668 | ``` 669 | 670 | next, we use these marker types and `PhantomData` to mark an array as having memory that is either 671 | initialized (`MI`), or uninitialized (`MU`). if no generic is given to `A`, i.e. `A`, it will 672 | use `MI` by default. 673 | 674 | ```rust 675 | use super::*; use std::marker::PhantomData as PD; 676 | #[derive(DBG)]pub struct A{/**columns*/ pub m:U, /**rows*/ pub n:U, 677 | /**data*/ d:*mut u8,/**layout*/ l:L, 678 | /**memory state*/i:PD, } 679 | ``` 680 | 681 | now, what benefits does this provide? 682 | 683 | it means that we can use `impl A{}` blocks to "gate" public interfaces, so that array access 684 | cannot be performed until an array has been initialized. `impl A` may in turn be used to 685 | provide interfaces that apply to _both_ uninitialized and initialized arrays. 686 | 687 | ```rust 688 | impl A{ 689 | pub fn get(&self,i:U,j:U)->R{Ok(unsafe{self.ptr_at(i,j)?.read()})} 690 | } 691 | impl A{ 692 | pub fn set(&mut self,i:U,j:U,v:I)->R<()>{unsafe{self.ptr_at(i,j)?.write(v);}Ok(())} 693 | pub(crate)fn ptr_at(&self,i:U,j:U)->R<*mut I>{self.ptr_at_impl(i,j,Self::index)} 694 | } 695 | ``` 696 | 697 | ...and finally, it means that we may mark certain interfaces as safe, or unsafe. for example, 698 | `A::init_with` provides a safe interface to initialize the memory of an array, using a callback 699 | that is given the position `(i,j)` of each cell. 700 | 701 | conversely, `A::set` may be used to manually initialize each position of the array, but places the 702 | onus upon the caller to determine whether or not each cell has been initialized. thus, `A::finish` 703 | is an unsafe interface, and must be called within an `unsafe{}` block. 704 | 705 | ```rust 706 | impl A{ 707 | pub fn new(m:U,n:U)->R{Self::alloc(m,n).map(|(l,d)|A{m,n,d,l,i:PD})} 708 | pub fn init_withR>(mut self,mut f:F)->R>{let(A{m,n,..})=self; 709 | for(i)in(1..=m){for(j)in(1..=n){let(v)=f(i,j)?;self.set(i,j,v)?;}}Ok(unsafe{self.finish()})} 710 | pub unsafe fn finish(self)->A{std::mem::transmute(self)} 711 | } 712 | ``` 713 | 714 | now, we can compare this to how this code might be formatted in common Rust, without such compact 715 | formatting and such short symbols: 716 | 717 | ```rust 718 | impl Array{ 719 | pub fn new(m: usize, n: usize) -> Result{ 720 | let (l, d) = Self::alloc(m, n)?; 721 | let a = A { m, n, d, l, i:PD }; 722 | Ok(a) 723 | } 724 | 725 | pub fn init_with(mut self, mut f: F) -> Result, anyhow::Error> 726 | where 727 | F: FnMut(usize, usize) -> Result 728 | { 729 | for i in 1..=self.m { 730 | for j in 1..=self.n { 731 | let v = f(i, j)?; 732 | self.set(i, j, v)?; 733 | } 734 | } 735 | let a = unsafe{ self.finish() }; 736 | Ok(a) 737 | } 738 | 739 | pub unsafe fn finish(self) -> Array { 740 | std::mem::transmute(self) 741 | } 742 | } 743 | ``` 744 | 745 | **these two snippets are not any mechanically different!** it bears consideration that this 746 | terse style did not prevent me from using familiar idioms. "_Whitney C_" may be a grand departure 747 | from other variants of C, but it _is_ still ultimately a dialect of C. "_Whitney Rust_" is also, 748 | at the end of the day, a dialect of Rust. 749 | 750 | ## 🏠 brevity is an architectural principal 751 | 752 | a core lesson i learned by building j is that this is extensive pursuit of brevity is about much 753 | more than syntactic brevity for cosmetic reasons. this is a kind of brevity that is also an 754 | architectural principal, and a mode of cognition. 755 | 756 | working like this had a perceptible impact on how i worked. it affected the tools i used, how i 757 | used them, and how i thought. 758 | 759 | **🔨 simple workflows** 760 | 761 | working with succinct code meant that i could rely on succinct workflows. when files are this 762 | short, you can print them with `cat`. remarkably simple. let's look at array indexing as another 763 | example. 764 | 765 | m×n arrays `A` have m rows and n columns, and are indexed with 1-based coordinates `(i,j)`. the 766 | top-left corner serves as the origin `(1,1)`. there is a documentation comment in `src/a.rs` on 767 | line 4 that shows this simple diagram: 768 | 769 | ``` 770 | [a_11, a_12, ... a_1n] 771 | [a_21, a_22, ... a_2n] 772 | [...., ...., ... ....] 773 | [a_m1, a_m2, ... a_mn] 774 | ``` 775 | 776 | when implementing new features, _especially_ when interacting with raw memory, i found that it was 777 | tremendously helpful to open this comment in a split window within my text editor, neovim. 778 | 779 | neovim have a `-c` option that may be used to run commands after opening a file. `+n` may be used 780 | to open a file at a particular line number. thus, nvim `+4 src/a.rs -c split -c res 4` would open 781 | the core `a.rs` array logic, with a split pane showing me this reference for my memory indexing 782 | strategy. 783 | 784 | rust's inline unit tests allowed me to often work with an entire subsystem _and_ its 785 | respective test suite on my screen at the same time. it is hard to overstate how novel and exciting 786 | this felt. 787 | 788 | **🌲 seeing the forest** 789 | 790 | i found that brevity changed the economy of space in my project away from _lines_ of code, into a 791 | two-dimensional economy of characters. while this use of horizontal alignment echoed what i have 792 | personally seen in plenty of C codebases, within succinct code i found that i was able to highlight 793 | commonalities and differences in higher-level parts of my software architecture: control flow, 794 | functions, etc. 795 | 796 | as an example, the `A` array type has two methods, `index` and `index_uc`, to convert 1-based 797 | `(i,j)` coordinates to the corresonding index of the raw allocated memory. `index` will check that 798 | the coordinates are in bounds. for performance reasons, the "_unchecked_" variant will elide this 799 | bounds check. 800 | 801 | look how clearly a succinct style highlights that difference: 802 | 803 | ```rust 804 | impl A{ 805 | fn index (&self,i:U,j:U)->R{self.oob(i,j)?;let A{m,n,..}=*self;let(i,j)=(i-1,j-1);Ok((i*n)+j)} 806 | fn index_uc(&self,i:U,j:U)->R{ let A{m,n,..}=*self;let(i,j)=(i-1,j-1);Ok((i*n)+j)} 807 | } 808 | ``` 809 | 810 | **🔎 brief reviews** 811 | 812 | cratelyn/j#10 introduces a new monadic verb, `>:`, to increment its given noun. 813 | 814 | `git show` has an option `--word-diff-regex` that can be used to control what a "word" is in the 815 | diff output. so `git show --word-diff-regex=.` is a way to see a per-character diff. using this, 816 | and the `-w --ignore-all-space` flag to ignore whitespace changes, this PR fits in one screen: 817 | 818 | ![`62edb1f8061cdcf859f9335e13fb6c104718a4e5`](./10-diff.png) 819 | 820 | > ❗ you can run `git show 62edb1f --ignore-all-space --word-diff-regex=.` if you would like to 821 | > see this in a local clone of this repository. 822 | 823 | you might naturally as a reviewer take some time to read through this change, and decide whether 824 | or not it looks good to you. this style does not mean that there is somehow _less code to review._ 825 | it does mean however, that you can see all of these changes at once. 826 | 827 | **💔 tooling incongruities** 828 | 829 | cratelyn/j#3 is an example of a very simple bugfix, fixing an off-by-one error for the `i.` verb. 830 | it replaces a `j` with a `(j-1)` in a particular expression. here is the diff, again using 831 | `--word-diff-regex=.`: 832 | 833 | ![`; git show --word-diff-regex=. --oneline fb72462 834 | fb72462 (origin/idot-should-start-from-zero, idot-should-start-from-zero) 🐛 bug: i. sequences should start from zero 835 | diff --git a/src/a.rs b/src/a.rs 836 | index 38f1d7b..f535c2c 100644 837 | --- a/src/a.rs 838 | +++ b/src/a.rs 839 | @@ -125,7 +125,7 @@ use super::*; use std::marker::PhantomData as PD; 840 | /**monadic verbs*/impl A{ 841 | pub fn m_idot(self)->R{let(a@A{m,n,..})=self;let gi=|i,j|a.get(i,j)?.try_into().map_err(E::from); 842 | if let(1,1)=(m,n){let(m,n)=(1,gi(1,1)?);let(mut o)=A::new(1,n)?; 843 | for(j)in(1..=n){o.set(1,j,{+(+}j{+-1)+}.try_into()?)?;}Ok(unsafe{o.finish()})} 844 | else if let(1,2)=(m,n){let(m,n)=(gi(1,1)?,gi(1,2)?); 845 | let(mut v)=0_u32;let(f)=move |_,_|{let(v_o)=v;v+=1;Ok(v_o)};A::new(m,n)?.init_with(f)} 846 | else{bail!("i. {m}x{n} not supported")}} 847 | diff --git a/tests/t.rs b/tests/t.rs 848 | index bb3b691..fa86b41 100644 849 | --- a/tests/t.rs 850 | +++ b/tests/t.rs 851 | @@ -20,7 +20,7 @@ 852 | #[test]fn $f()->R<()>{let(a@A{m:1,n:1,..})=eval_s($i)? else{bail!("bad dims")};eq!(a.as_slice()?,&[$o]);ok!()}}} 853 | t!(tally_scalar,"# 1",1);t!(tally_1x3,"# 1 2 3",3);t!(tally_3x3,"# i. 3 3",9); 854 | } #[cfg(test)]mod idot{use super::*; 855 | #[test]fn idot_3()->R<()>{let(a)=eval_s("i. 3")?;eq!(a.m,1);eq!(a.n,3);eq!(a.as_slice()?,&[{+0,+}1,2[-,3-]]);ok!()} 856 | #[test]fn idot_2_3()->R<()>{let(a)=eval_s("i. 2 3")?;eq!(a.m,2);eq!(a.n,3);let o:&[&[I]]=&[&[0,1,2],&[3,4,5]]; 857 | eq!(a.into_matrix()?,o);eq!(a,o);ok!()} 858 | #[test]fn idot_3_2()->R<()>{let(a)=eval_s("i. 3 2")?;eq!(a.m,3);eq!(a.n,2);let o:&[&[I]]=&[&[0,1],&[2,3],&[4,5]];`](./3-diff.png) 859 | 860 | > ❗ you can run `git show fb72462 --oneline --word-diff-regex=.` if you would like to see this in 861 | > a local clone of this repository. 862 | 863 | this diff, when shown with `--oneline` and `--word-diff-regex=.`, is 1442 characters. 864 | only 24 characters are the changes themselves (_including `{+` and `+}` markers_). only 16 865 | characters would be needed to print the names of the files shown. 866 | 867 | this is of course, napkin math, but that means that more than 97% of the diff is _context._ the 868 | homogeneity of so many programming languages in industry today doesn't just affect the way we 869 | write code. these preconceptions become assumptions that are baked into the tools we use. 870 | thus, git is showing me "context" that presumes we are measuring of code in terms of "lines". 871 | 872 | ## 🖤 conclusion 873 | 874 | overall, i enjoyed working in this style. it provided me with a fresh perspective about how i 875 | use the computer, what language can look like, and how notation affects the way we think. 876 | if you have ever been curious about array programming languages, i recommend you give them a try. 877 | 878 | --- 879 | 880 | ### 🔗 works cited 881 | 882 | * ["Future Proofing"](https://rust-lang.github.io/api-guidelines/future-proofing.html) 883 | * ["New Type Idiom"](https://doc.rust-lang.org/rust-by-example/generics/new_types.html) 884 | * ["Incunabulum"](https://code.jsoftware.com/wiki/Essays/Incunabulum) 885 | * ["J: Gerunds And Atomic Representation"](https://code.jsoftware.com/wiki/Vocabulary/GerundsAndAtomicRepresentation) 886 | * ["J: Getting Started"](https://code.jsoftware.com/wiki/Guides/Getting_Started) 887 | * ["J: NuVoc"](https://code.jsoftware.com/wiki/NuVoc) 888 | * ["The language strangeness budget"](https://steveklabnik.com/writing/the-language-strangeness-budget) 889 | * ["Why K"](https://xpqz.github.io/kbook/Introduction.html#why-k) 890 | * ["Why Rust’s postfix await syntax is good"](https://blog.ceejbot.com/posts/postfix-await/) 891 | * rust-lang/rust#57640 892 | * https://github.com/rust-lang/rust/issues/57640 893 | * https://github.com/rust-lang/rust/issues/50547 894 | * ["Does APL Need A Type System?"](https://www.youtube.com/watch?v=z8MVKianh54) 895 | 896 | [api-guidelines-futureproof]: https://rust-lang.github.io/api-guidelines/future-proofing.html 897 | [api-guidelines-newtype]: https://doc.rust-lang.org/rust-by-example/generics/new_types.html 898 | [incunabulum]: https://code.jsoftware.com/wiki/Essays/Incunabulum 899 | [j-gerunds]: https://code.jsoftware.com/wiki/Vocabulary/GerundsAndAtomicRepresentation 900 | [j-getting-started]: https://code.jsoftware.com/wiki/Guides/Getting_Started 901 | [j-nuvoc]: https://code.jsoftware.com/wiki/NuVoc 902 | [klabnik-budget]: https://steveklabnik.com/writing/the-language-strangeness-budget 903 | [why-k]: https://xpqz.github.io/kbook/Introduction.html#why-k 904 | [ceej-postfix]: https://blog.ceejbot.com/posts/postfix-await/ 905 | [rust-57640]: https://github.com/rust-lang/rust/issues/57640 906 | [rust-50547]: https://github.com/rust-lang/rust/issues/50547 907 | [hsu-apl]: https://www.youtube.com/watch?v=z8MVKianh54 908 | -------------------------------------------------------------------------------- /src/a.rs: -------------------------------------------------------------------------------- 1 | use super::*; use std::marker::PhantomData as PD; 2 | /// === mxn array === (a_ij) : 1<=i<=m, 1<=j<=n 3 | /// ```text 4 | /// [a_11, a_12, ... a_1n] 5 | /// [a_21, a_22, ... a_2n] 6 | /// [...., ...., ... ....] 7 | /// [a_m1, a_m2, ... a_mn] 8 | /// ``` 9 | #[derive(DBG)]pub struct A{/**columns*/ pub m:U, /**rows*/ pub n:U, 10 | /**data*/ d:*mut u8,/**layout*/l:L, 11 | /**memory state*/i:PD, } 12 | 13 | /**memory indexing*/mod i{use super::*; 14 | impl A{ 15 | fn oob(&self,i:U,j:U)->R<()>{let A{m,n,..}=*self; 16 | if(i==0||j==0||i>m||j>n){bail!("({i},{j}) is out-of-bounds of ({m},{n})")}ok!()} 17 | /// returns the scalar `A_ij` within this array. returns an error if position is out-of-bounds. 18 | pub fn index(&self,i:U,j:U)->R {self.oob(i,j)?;let(i,j)=(i-1,j-1);Ok((i*self.n)+j)} 19 | /// returns the scalar `A_ij` within this array. does not check if the position is in bounds. 20 | pub fn index_uc(&self,i:U,j:U)->R{ let(i,j)=(i-1,j-1);Ok((i*self.n)+j)} 21 | } 22 | // === test helpers === 23 | /// `A::index` test case generator. check that indexing at a position returns the expected value. 24 | #[macro_export] macro_rules! ti{($f:ident,$a:ident,$i:literal,$j:literal,$o:literal)=> 25 | {#[test]fn $f()->R<()>{eq!($a()?.index($i,$j)?,$o);ok!()}}} 26 | /// `A::index` test case generator. check that indexing an out-of-bounds position returns an error. 27 | #[macro_export] macro_rules! toob{($f:ident,$a:ident,$i:literal,$j:literal)=> 28 | {#[test] fn $f()->R<()>{is!($a()?.index($i,$j).is_err());ok!()}}} 29 | // === 1x1 array indexing === 30 | #[cfg(test)] fn sca()->R{let Ok(a@A{m:1,n:1,..})=A::from_i(42)else{bail!("bad dims")};Ok(a)} 31 | toob!(i00_for_scalar,sca,0,0);toob!(i10_for_scalar,sca,1,0);toob!(i01_for_scalar,sca,0,1); 32 | toob!(i21_for_scalar,sca,2,1);toob!(i12_for_scalar,sca,1,2);toob!(i22_for_scalar,sca,2,2); 33 | ti!(i11_for_scalar,sca,1,1,0); 34 | // === 2x3 array indexing === 35 | #[cfg(test)] fn arr2x3()->R{let Ok(a@A{m:2,n:3,..})=A::zeroed(2,3)else{bail!("bad dims")};Ok(a)} 36 | toob!(i00_for_2x3,arr2x3,0,0);toob!(i01_for_2x3,arr2x3,0,1);toob!(i10_for_2x3,arr2x3,1,0); 37 | ti!(i11_for_2x3,arr2x3,1,1,0);ti!(i12_for_2x3,arr2x3,1,2,1);ti!(i13_for_2x3,arr2x3,1,3,2); 38 | ti!(i21_for_2x3,arr2x3,2,1,3);ti!(i22_for_2x3,arr2x3,2,2,4);ti!(i23_for_2x3,arr2x3,2,3,5); 39 | // === 3x3 array indexing === 40 | #[cfg(test)] fn arr3x3()->R{let Ok(a@A{m:3,n:3,..})=A::zeroed(3,3)else{bail!("bad dims")};Ok(a)} 41 | toob!(i00_for_3x3,arr3x3,0,0);toob!(i01_for_3x3,arr3x3,0,1);toob!(i14_for_3x3,arr3x3,1,4); 42 | toob!(i41_for_3x3,arr3x3,4,1);toob!(i44_for_3x3,arr3x3,4,4); 43 | ti!(i11_for_3x3,arr3x3,1,1,0);ti!(i21_for_3x3,arr3x3,2,1,3);ti!(i22_for_3x3,arr3x3,2,2,4); 44 | ti!(i31_for_3x3,arr3x3,3,1,6);ti!(i33_for_3x3,arr3x3,3,3,8); } 45 | 46 | /**array allocation*/mod alloc{use{super::*,std::alloc::{alloc,alloc_zeroed,dealloc}}; 47 | /**sealed trait, memory markers*/pub trait MX{} impl MX for MU {} impl MX for MI {} 48 | /**marker: memory uninitialized*/#[derive(CL,DBG)]pub struct MU; 49 | /**marker: memory initialized*/ #[derive(CL,DBG)]pub struct MI; 50 | impl A{ 51 | pub fn new(m:U,n:U)->R{Self::alloc(m,n).map(|(l,d)|A{m,n,d,l,i:PD})} 52 | pub fn init_withR>(mut self,mut f:F)->R>{let(A{m,n,..})=self; 53 | for(i)in(1..=m){for(j)in(1..=n){let(v)=f(i,j)?;self.set(i,j,v)?;}}Ok(unsafe{self.finish()})} 54 | pub unsafe fn finish(self)->A{std::mem::transmute(self)}} 55 | impl A{ 56 | pub fn zeroed(m:U,n:U)->R{let(l,d)=Self::allocz(m,n)?;Ok(A{m,n,d,l,i:PD})} 57 | pub fn from_i(i:I)->R{let mut a=A::new(1,1)?;a.set(1,1,i)?;Ok(unsafe{a.finish()})}} 58 | impl TF for A{type Error=E;fn try_from(i:I)->R{A::from_i(i)}} 59 | impl A{ 60 | fn alloc (m:U,n:U)->R<(L,*mut u8)>{let(l)=Self::l(m,n)?;let d=unsafe{alloc(l)}; Ok((l,d))} 61 | fn allocz(m:U,n:U)->R<(L,*mut u8)>{let(l)=Self::l(m,n)?;let d=unsafe{alloc_zeroed(l)};Ok((l,d))} 62 | fn l(m:U,n:U)->R{L::array::(m*n).map_err(E::from)}} 63 | impl Drop for A{fn drop(&mut self){let(A{d,l,..})=self;unsafe{dealloc(*d,*l)}}} 64 | } pub use self::alloc::{MI,MU,MX}; 65 | 66 | /**array access*/mod access{use{super::*,std::mem::size_of}; 67 | impl A{ // only allow read access for initialized arrays 68 | pub fn get(&self,i:U,j:U)->R{Ok(unsafe{self.ptr_at(i,j)?.read()})} 69 | pub fn get_uc(&self,i:U,j:U)->R{Ok(unsafe{self.ptr_at_uc(i,j)?.read()})} 70 | /// returns an iterator whose elements are tuples (i,j) across the array's positions. 71 | pub fn iter(&self)->impl IT{let A{m,n,..}=*self;(1..=m).flat_map(move|i|(1..=n).map(move|j|(i,j)))} 72 | pub fn vals<'a>(&'a self)->impl IT + 'a{let A{m,n,..}=*self; 73 | (1..=m).flat_map(move|i|(1..=n).map(move|j|self.get_uc(i,j).expect("reads work")))}} 74 | impl A{ 75 | /// sets the value at the given position. 76 | pub fn set(&mut self,i:U,j:U,v:I)->R<()>{unsafe{self.ptr_at(i,j)?.write(v);}Ok(())} 77 | /// returns a raw pointer to the underlying array memory at (i,j). returns an error if position is out-of-bounds. 78 | pub(crate)fn ptr_at(&self,i:U,j:U)->R<*mut I>{self.ptr_at_impl(i,j,Self::index)} 79 | /// returns a raw pointer to the underlying array memory at (i,j). does not check if position is in bounds. 80 | pub(crate)fn ptr_at_uc(&self,i:U,j:U)->R<*mut I>{self.ptr_at_impl(i,j,Self::index_uc)} 81 | fn ptr_at_implR>(&self,i:U,j:U,f:F)->R<*mut I>{ 82 | let(o):isize=f(self,i,j).map(|x|x*size_of::())?.try_into()?;let(d)=unsafe{(self.d.offset(o) as *mut I)}; 83 | Ok(d)}}} 84 | 85 | /**scalar conversion/comparison*/mod scalars{use super::*; /*todo...*/ 86 | impl A{pub fn as_i(&self)->R{let a@A{m:1,n:1,..}=self else{bail!("not a scalar")};a.get(1,1)}} 87 | #[test]fn scalar_get()->R<()>{let a=A::from_i(42)?;eq!(a.get(1,1)?,42);drop(a);ok!()} 88 | #[test]fn scalar_set()->R<()>{let mut a=A::from_i(42)?;a.set(1,1,420)?;eq!(a.get(1,1)?,420);drop(a);ok!()}} 89 | 90 | /**slices conversion/comparison*/mod slices{use super::*; 91 | impl A{ // only allow slice access for initialized arrays 92 | pub fn as_slice(&self)->R<&[I]>{let(A{m:1,n:l,d,..}|A{m:l,n:1,d,..})=(self)else{bail!("not a slice")}; 93 | Ok(unsafe{from_raw_parts(*d as *mut I,*l as U)})}} 94 | impl PE<&[I]> for A{fn eq(&self,r:&&[I])->bool{self.as_slice().map(|s|s.eq(*r)).unwrap_or(false)}} 95 | impl TF<&[I]> for A{type Error=E;fn try_from(s:&[I])->R{ 96 | let(m,n)=(1,s.len());let(mut a)=A::new(m,n)?; 97 | for(i,v)in(s.iter().enumerate()){let(i)=(i+1).try_into()?;a.set(1,i,*v)?;}Ok(unsafe{a.finish()})}} 98 | impl TF> for A{type Error=E;fn try_from(v:V)->R{v.as_slice().try_into()}} 99 | #[test]fn scalars_can_be_a_slice()->R<()>{let(a)=A::from_i(420)?;let _:&[I]=a.as_slice()?;ok!()} 100 | #[test]fn from_empty()->R<()>{let a:&[I]=&[];let _=A::try_from(a)?;ok!()} 101 | #[test]fn from_one()->R<()>{let a:&[I]=&[42];let a=A::try_from(a)?;eq!(a.get(1,1)?,42);ok!()} 102 | #[test]fn from_three()->R<()>{let a:&[I]=&[7,8,9];let a=A::try_from(a)?; 103 | eq!(a.get(1,1)?,7);eq!(a.get(1,2)?,8);eq!(a.get(1,3)?,9);is!(a.get(1,0).is_err());is!(a.get(1,4).is_err());ok!()} 104 | #[test]fn eq_three()->R<()>{let(s):&[I]=&[1,2,3];let(a)=(A::try_from(s)?);eq!(a,s);ok!()} 105 | #[test]fn neq_three()->R<()>{let(s,o):(&[I],&[I])=(&[1,2],&[2,3]);let(a)=(A::try_from(s)?);neq!(a,o);ok!()} 106 | #[test]fn neq_prefix()->R<()>{let(s,o):(&[I],&[I])=(&[1,2],&[1,2,3]);let(a)=(A::try_from(s)?);neq!(a,o);ok!()} 107 | #[test]fn column_slice_can_be_a_slice()->R<()>{let(a):&[I]=&[7,8,9]; 108 | let(a@A{m:3,n:1,..})=A::try_from(a)?.m_trans()?else{bail!("bad dims")};eq!(a.as_slice()?,&[7,8,9]);ok!()}} 109 | 110 | /**matrix conversion/comparison*/mod matrices{use super::*; 111 | impl A{ // only allow matrix access for initialized arrays 112 | pub fn into_matrix(&self)->R>{let(A{m,n,..})=*self; 113 | (0..m).map(|m|{self.ptr_at(m+1,1)}).map(|r|r.map(|d|unsafe{from_raw_parts(d as *mut I, n as U)})).collect()}} 114 | impl PE<&[&[I]]> for A{fn eq(&self,r:&&[&[I]])->bool{ 115 | if(r.len()!=self.m){r!(false)}for(i,r_i)in(r.into_iter().enumerate()){ 116 | if(r_i.len()!=self.n){r!(false)}for(j,r_ij)in(r_i.into_iter().enumerate()){ 117 | let(i,j)=(i+1,j+1);let(a_ij)=match(self.get(i,j)){Ok(v)=>v,Err(_)=>r!(false)}; 118 | if(a_ij)!=(*r_ij){r!(false)}}}true}}} 119 | 120 | /**monadic verbs*/impl A{ 121 | pub fn m_same(self)->R{Ok(self)} 122 | pub fn m_idot(self)->R{let(a@A{m,n,..})=self;let gi=|i,j|a.get(i,j)?.try_into().map_err(E::from); 123 | if let(1,1)=(m,n){let(n)=(gi(1,1)?);let(mut o)=A::new(1,n)?; 124 | for(j)in(1..=n){o.set(1,j,(j-1).try_into()?)?;}Ok(unsafe{o.finish()})} 125 | else if let(1,2)=(m,n){let(m,n)=(gi(1,1)?,gi(1,2)?); 126 | let(mut v)=0_u32;let(f)=move |_,_|{let(v_o)=v;v+=1;Ok(v_o)};A::new(m,n)?.init_with(f)} 127 | else{bail!("i. {m}x{n} not supported")}} 128 | pub fn m_shape(self)->R{let(A{m,n,..})=self;let(a):&[I]=&[m as I,n as I];A::try_from(a)} 129 | pub fn m_tally(self)->R{let A{m,n,..}=self;let(i)=I::try_from(m*n)?;A::from_i(i)} 130 | pub fn m_trans(self)->R{let(i@A{m:m_i,n:n_i,..})=self;let(m_o,n_o)=(n_i,m_i); 131 | let(f)=|i_o,j_o|{i.get(j_o,i_o)};A::new(m_o,n_o)?.init_with(f)} 132 | pub fn m_inc(self)->R{let(a@A{m,n,..})=self;A::new(m,n)?.init_with(|i,j|a.get(i,j).map(|x|x+1))}} 133 | 134 | /**dyadic verbs*/impl D{ 135 | /*return dyad function**/ pub fn f(&self)->fn(I,I)->I{use D::*; 136 | match(self){Plus=>D::add, Mul=>D::mul, Left=>D::left, Right=>D::right} } 137 | /*add two numbers*/fn add (x:I,y:I)->I{x+y} /*multiply two numbers*/fn mul (x:I,y:I)->I{x*y} 138 | /*left */fn left(x:I,_:I)->I{x } /*right */fn right(_:I,y:I)->I{ y} 139 | } impl A{ 140 | pub fn d_left (self,_:A)->R{Ok(self) } 141 | pub fn d_right(self,r:A)->R{Ok(r) } 142 | pub fn d_plus(self,r:A) ->R{A::d_do(self,r,D::add)} 143 | pub fn d_mul (self,r:A) ->R{A::d_do(self,r,D::mul)} 144 | pub fn d_do(l@A{m:ml,n:nl,..}:A,r@A{m:mr,n:nr,..}:A,f:impl Fn(I,I)->I)->R>{ 145 | let(li,ri)=(l.as_i().ok(),r.as_i().ok());let(ls,rs)=(l.as_slice().ok(),r.as_slice().ok()); 146 | if let(Some(li),Some(ri))=(li,ri){r!(A::from_i(f(li,ri)))} // two scalars 147 | else if let(_,Some(s),None,a@A{m,n,..})|(a@A{m,n,..},None,Some(s),_)=(&l,li,ri,&r) // scalar and array 148 | {let(f)=|i,j|{Ok(f(a.get(i,j)?,s))};r!(A::new(*m,*n)?.init_with(f))} 149 | else if let(_,Some(s),None,a@A{m,n,..})|(a@A{m,n,..},None,Some(s),_)=(&l,ls,rs,&r) // slice and array 150 | {if(s.len()==*m){let(f)=|i,j|{let(x)=a.get(i,j)?;let(y)=(s[i-1]);Ok(f(x,y))};r!(A::new(*m,*n)?.init_with(f))}} 151 | else if (ml==mr)&&(nl==nr){let(m,n)=(ml,nl);r!(A::new(m,n)?.init_with( // matching arrays 152 | |i,j|{let(l,r)=(l.get(i,j)?,r.get(i,j)?);Ok(f(l,r))}))} 153 | else if (ml==nr)&&(nl==mr) /*NB: inherit the dimensions of the right-hand operand.*/ // rotation 154 | {let(f)=|i,j|{let(x)=l.get(j,i)?;let(y)=r.get(i,j)?;Ok(f(x,y))};r!(A::new(mr,nr)?.init_with(f))} 155 | bail!("length error"); 156 | }} 157 | 158 | /**monadic adverbs*/mod adverbs_m{use super::*; 159 | impl Ym{ 160 | /// using this adverb, apply the given dyadic verb to the provided operand. 161 | pub fn apply(&self,d:D,a:A)->R{use Ym::*;match(self){Insert=>Ym::insert(d,a),Prefix=>Ym::prefix(d,a)}} 162 | fn insert(d:D,a:A)->R{let mut v=a.vals();let(i)=v.next().ok_or(err!("empty"))?;v.fold(i,d.f()).try_into()} 163 | fn prefix(d:D,a:A)->R{ 164 | let d_=|i|{use{D::*};match(d){Mul=>1,_=>i}}; 165 | if let Ok(i)=a.as_i() {A::from_i(d_(i))} 166 | else if let Ok(s)=a.as_slice(){let (m,n)=(s.len(),s.len()); 167 | let p=|i,j|if(j>i){Ok(0)}else{a.get(1,j).map(d_)}; 168 | A::new(m,n)?.init_with(p)} 169 | else { bail!("monadic `\\` is not implemented for matrices") }}} 170 | // === monadic `/`, `Ym::Insert` tests 171 | macro_rules! test_insert{($f:ident,$d:expr,$a:expr,$o:expr)=> 172 | {#[test]fn $f()->R<()>{let(a):R={$a};let(d):D={$d}; // typecheck macro arguments. 173 | let i:I=a.and_then(|a:A|Ym::insert(d,a)).and_then(|a|a.as_i())?; 174 | eq!(i,$o);ok!()}}} 175 | test_insert!(add_a_scalar, D::Plus, A::from_i(42), 42 ); 176 | test_insert!(add_a_sequence, D::Plus, >::try_from(&[1,2,3,4,5]), (1+2+3+4+5) ); 177 | test_insert!(mul_a_sequence, D::Mul , >::try_from(&[1,2,3,4,5]), (1*2*3*4*5) ); } 178 | 179 | /**dyadic adverbs*/mod adverbs_d{use super::*; 180 | impl Yd{ 181 | /// using this adverb, apply the given dyadic verb to the provided operand. 182 | pub fn apply(&self,d:D,l:A,r:A)->R{use Yd::*;match(self){Table=>Yd::table(d,l,r),Infix=>Yd::infix(d,l,r)}} 183 | fn table(d:D,l:A,r:A)->R{let (l_i,r_i)=(l.as_i() ,r.as_i()); 184 | let (l_s,r_s)=(l.as_slice(),r.as_slice()); 185 | if let (Ok(l),Ok(r))=(l_i,r_i){let(i)=d.f()(l,r);A::from_i(i)} 186 | else if let (Ok(l),Ok(r))=(l_s,r_s){let(m,n)=(l.len(),r.len());let(d)=d.f(); 187 | let f=|i,j|->R{let(x,y)=(l[i-1],r[j-1]);Ok(d(x,y))}; 188 | A::new(m,n)?.init_with(f)} 189 | else {bail!("unexpected fallthrough in Yd::table")}} 190 | fn infix(_:D,l:A,r:A)->R{let(s)=r.as_slice().map_err(|_|err!("infix rhs must be a slice"))?; 191 | let(il)=l.as_i() .map_err(|_|err!("infix lhs must be a scalar"))?.try_into()?; 192 | let(ic)=(s.len()-il)+1; 193 | A::new(ic,il)?.init_with(|i,j|Ok(s[(i-1)+(j-1)]))}}} 194 | 195 | /**deep-copy*/impl A{pub fn deep_copy(&self)->R{A::new(self.m,self.n)?.init_with(|i,j|{self.get(i,j)})}} 196 | 197 | /**display*/mod fmt{use super::*; 198 | impl DS for A{ 199 | fn fmt(&self,fmt:&mut FMT)->FR{let A{n,..}=*self;for(i,j)in(self.iter()) 200 | {let(x)=self.get_uc(i,j).map_err(|_|std::fmt::Error)?;write!(fmt,"{x}{}",if(j==n){'\n'}else{' '})?;}ok!()}}} 201 | -------------------------------------------------------------------------------- /src/j.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_parens)] /**prelude*/mod p;use p::*; /*test prelude*/#[cfg(test)]use p::tp::*; 2 | /**symbol table*/mod s; /**array*/ mod a; /**lex/parse input*/mod r;use r::*; 3 | pub use self::{a::*,s::*}; 4 | pub fn eval(input:&str,st:&mut ST)->R>{ 5 | let(mut ts)=lex(input)?;let(ast)=match(parse(&mut ts)?){Some(x)=>x,None=>rrn!()};eval_(ast,st)} 6 | fn eval_(ast:B,st:&mut ST)->R>{use{M::*,D::*}; 7 | let(mut rec)=|a|->R{match(eval_(a,st)){Ok(Some(a))=>Ok(a),Err(e)=>Err(e),/*recursively evaluate*/ 8 | Ok(None)=>Err(err!("expression did not result in a value"))}}; 9 | match *ast{N::A{a}=>Ok(a), // array literal 10 | N::M{m,o }=>{let(a)=rec(o)?; match m{Idot=>a.m_idot(),Shape=>a.m_shape(),Transpose=>a.m_trans(), // monadic verb 11 | Same=>a.m_same(),Tally=>a.m_tally(),Inc=>a.m_inc()}} 12 | N::D{d,l,r }=>{let(l,r)=(rec(l)?,rec(r)?);match d{Plus=>l.d_plus(r),Mul=>l.d_mul(r), // dyadic verb 13 | Left=>l.d_left(r),Right=>l.d_right(r)}} 14 | N::Ym{ym,d,o }=>{rec(o).and_then(|a|ym.apply(d,a))} // monadic adverb 15 | N::Yd{yd,d,l,r}=>{let(l,r)=(rec(l)?,rec(r)?);yd.apply(d,l,r)} // dyadic adverb 16 | N::E {sy,e }=>{let(a)=rec(e)?;st.insert(sy,a);r!(Ok(None))} // symbol assignment 17 | N::S {sy }=>{st.get(&sy).ok_or(err!("undefined symbol: {sy:?}")).and_then(A::deep_copy)} // symbol 18 | }.map(O::Some)} 19 | -------------------------------------------------------------------------------- /src/p.rs: -------------------------------------------------------------------------------- 1 | #![allow(unused_imports)] //! prelude; shorthand aliases for common types and traits, macros for common patterns. 2 | pub(crate)use{Box as B,char as C,u32 as I,usize as U,Option as O,String as S,TryFrom as TF,TryInto as TI,Vec as V}; 3 | pub(crate)use{std::{alloc::Layout as L,clone::Clone as CL,cmp::{PartialEq as PE,PartialOrd as PO}, 4 | collections::{BTreeMap as BM,VecDeque as VD},fmt::{Debug as DBG,Display as DS,Formatter as FMT,Result as FR}, 5 | iter::{FromIterator as FI,IntoIterator as IIT,Iterator as IT},io::stdin, 6 | slice::{from_raw_parts,from_raw_parts_mut},str::FromStr as FS}}; 7 | pub(crate)use{anyhow::{Context,Error as E,anyhow as err,bail}}; 8 | #[macro_export] /**`return`*/ macro_rules! r {()=>{return};($e:expr)=>{return $e};} 9 | #[macro_export] /**`return Ok(Some(..))`*/ macro_rules! rro {($e:expr)=>{r!(Ok(Some($e)))}} 10 | #[macro_export] /**`return Ok(None)`*/ macro_rules! rrn {( )=>{r!(Ok(None ))}} 11 | #[macro_export] /**`Ok(())`*/ macro_rules! ok {()=>{Ok(())}} 12 | #[macro_export] /**`Box::new(..)`*/ macro_rules! b {($e:expr)=>{B::new($e)};} 13 | #[macro_export] /**`unreachable!()`*/ macro_rules! ur {()=>{unreachable!()}} 14 | /**`Result`*/ pub type R = Result; 15 | #[cfg(test)]/**test prelude*/pub(crate) mod tp{ 16 | pub(crate) use{assert_eq as eq,assert_ne as neq,assert as is,vec as v}; } 17 | -------------------------------------------------------------------------------- /src/r.rs: -------------------------------------------------------------------------------- 1 | /**input lexing*/ pub(crate) use self::{lex::lex,parse::{D,M,N,Yd,Ym,parse}}; 2 | mod lex{use crate::*; 3 | /**syntax token*/ #[derive(CL,DBG,PE)] pub(crate) enum T {/*array literal*/A(V), 4 | /*assignment*/ E , 5 | /* NB: this does not identify whether possible verbs */ /*(ad)verb*/ V(S) , 6 | /* are monadic or dyadic. that is done during parsing.*/ /*symbol*/ SY(SY) } 7 | pub(crate) fn lex(input:&str)->R>{ 8 | let(mut ts)=input.split_whitespace().peekable(); let(mut o)=V::with_capacity(ts.size_hint().0); 9 | while let Some(t) =ts.next(){ 10 | if t == "=:" {o.push(T::E)} // assignment 11 | else if let Some(sy) =t.parse().ok().map(T::SY){o.push(sy);} // symbol 12 | else if let Some(mut v)=t.parse().ok().map(|i|vec![i]){ // array literal 13 | macro_rules! peek{()=>{ts.peek().and_then(|t|t.parse().ok())}} // ..is the next token a number? 14 | macro_rules! put{($i:ident)=>{ts.next().map(drop);v.push($i);}} // ..append to our array literal 15 | while let Some(i)=peek!(){put!(i);} o.push(T::A(v));} 16 | else {o.push(T::V(S::from(t)))} // otherwise, a verb or adverb 17 | } r!(Ok(o)) } 18 | #[cfg(test)]mod t{use super::{*,T::A as TA,T::V as TV}; 19 | /// test helper: lex an expression and check the output 20 | macro_rules! t{($f:ident,$i:literal,$o:expr)=>{#[test]fn $f()->R<()>{eq!(lex($i)?,$o);ok!()}}} 21 | macro_rules! sy{($i:literal)=>{$i.parse().map(T::SY).unwrap()}} 22 | // === lexing unit tests === 23 | t!(lex_1, "1", v![TA(v![1])] ); 24 | t!(lex_9, "9", v![TA(v![9])] ); 25 | t!(lex_1to3, "1 2 3", v![TA(v![1,2,3])] ); 26 | t!(lex_monad, "# 1 2 3", v![TV(S::from("#")), TA(v![1,2,3])] ); 27 | t!(lex_dyad, "1 + 2", v![TA(v![1]), TV(S::from("+")), TA(v![2])] ); 28 | t!(lex_two_verbs, "1 + # 1 2 3", v![TA(v![1]), TV(S::from("+")), TV(S::from("#")), TA(v![1,2,3])] ); 29 | t!(sum_over, "+ / 1 2", v![TV(S::from("+")), TV(S::from("/")), TA(v![1,2])] ); 30 | t!(lex_symbol, "abc", v![sy!("abc")] ); 31 | t!(lex_assign, "a =: 1", v![sy!("a"), T::E, TA(v![1])] ); 32 | } 33 | }/**input parsing*/mod parse{use {crate::*,super::lex::T}; 34 | /**dyadic verb */ #[derive(DBG,PE,PO)] pub enum D {Plus,Mul, Left, Right } 35 | /**monadic verb */ #[derive(DBG,PE,PO)] pub enum M {Idot,Shape,Tally,Transpose,Same,Inc} 36 | /**dyadic adverb */ #[derive(DBG )] pub enum Yd{/**dyadic `/` */ Table , 37 | /**dyadic `\` */ Infix } 38 | /**monadic adverb */ #[derive(DBG )] pub enum Ym{/**monadic `/`*/ Insert, 39 | /**monadic `\`*/ Prefix} 40 | /**ast node */ #[derive(DBG, )] pub enum N {/**array literal*/ A{a:A}, 41 | /**dyadic verb*/ D{d:D,l:B,r:B}, 42 | /**monadic verb*/ M{m:M,o:B}, 43 | /**dyadic adverb*/ Yd{yd:Yd,d:D,l:B,r:B}, 44 | /**monadic adverb*/ Ym{ym:Ym,d:D,o:B}, 45 | /**symbol*/ S{sy:SY}, 46 | /**symbol assignment*/E{sy:SY,e:B}} 47 | impl From for N{fn from(sy:SY)->N{N::S{sy}}} 48 | impl TF> for N{type Error=E; fn try_from(a:Vec)->R{a.try_into().map(|a|N::A{a})}} 49 | /**parse a sequence of tokens into an abstract syntax tree.*/ 50 | pub(crate) fn parse(ts:&mut V)->R>>{const MAX:u32=128;let(mut ctx,mut i)=(V::new(),0); 51 | while(!ts.is_empty()){if(i>MAX){bail!("max iterations")}parse_(ts,&mut ctx)?;i+=1;} 52 | /*debug*/debug_assert!(ts.is_empty());debug_assert!(ctx.len() <= 1,"AST needs a root node: {ctx:?}");/*debug*/ 53 | Ok(ctx.pop())} 54 | fn parse_(ts:&mut V,ctx:&mut V>)->R<()>{ 55 | // push a new AST node onto the `ctx` stack and return, indicating a successful parsing "step." 56 | macro_rules! step{($n:expr)=>{ctx.push(b!($n));r!(ok!());}} 57 | let(v):S=match ts.pop(){ 58 | Some(T::V(v)) =>v, /*take the next verb, or return if done*/ None=>r!(ok!()), 59 | Some(T::A(v)) =>{let(n)=v.try_into()?;step!(n);} // array literal 60 | Some(T::SY(sy))=>{let(n)=sy.into(); step!(n);} // symbol name 61 | Some(T::E) =>{let Some(T::SY(sy))=ts.pop()else{bail!("assignment must apply to a symbol")}; 62 | /*assignment*/ let(e)=ctx.pop().ok_or(err!("assignment missing right-hand side"))?; 63 | step!(N::E{sy,e});}}; 64 | let(rhs)=ctx.pop().ok_or(err!("no right-hand operand for `{v:?}`"))?; /*right-hand operand*/ 65 | let(lhs):O>=match ts.pop(){ /*take the left-hand operand, if it exists. */ 66 | None =>{ None} Some(T::A(v)) =>Some(b!(v.try_into()?)), 67 | Some(t@T::V(_)|t@T::E)=>{ts.push(t);None} Some(T::SY(sy)) =>Some(b!(sy.into())), 68 | }; 69 | /*first, process monadic and dyadic verbs*/ 70 | if let Some(l)=lhs{let(d)=D::new(&v).ok_or(err!("invalid dyad {v:?}"))?;step!(N::D{l,r:rhs,d});} 71 | else if let Some(m)=M::new(&v){step!(N::M{m,o:rhs});} 72 | /*otherwise, we should treat this as an adverb*/ 73 | let(y)=v;let(d)=ts.pop().ok_or(err!("adverbs need a verb to apply"))?; 74 | macro_rules! ym {()=>{ 75 | let(ym)=Ym::new(&y).ok_or(err!("invalid monadic adverb {y:?}"))?; 76 | let(d)=match(d){T::V(ref d)=>D::new(d),_=>None}.ok_or(err!("invalid dyadic verb {d:?} for adverb {y:?}"))?; 77 | step!(N::Ym{ym,d,o:rhs}); 78 | }} 79 | macro_rules! yd {($l:ident)=>{ 80 | let(yd)=Yd::new(&y).ok_or(err!("invalid dyadic adverb {y:?}"))?; 81 | let(d)=match(d){T::V(ref d)=>D::new(d),_=>None}.ok_or(err!("invalid dyadic verb {d:?} for adverb {y:?}"))?; 82 | step!(N::Yd{yd,d,l:$l,r:rhs}); 83 | }} 84 | match(ts.pop()){ /*confirm the arity by examining the left-hand operand (NB: put it back if you don't need it!)*/ 85 | /*monadic adverb*/ /*dyadic adverb */ 86 | None =>{ ym!();} Some(T::A(v)) =>{let(l)=b!(v.try_into()?);yd!(l);} 87 | Some(t@T::E|t@T::V(_))=>{ts.push(t);ym!();} Some(T::SY(sy))=>{let(l)=b!(sy.into()); yd!(l);} 88 | }} 89 | impl M {fn new(s:&str)->O {use M::*; Some(match s{"i."=>Idot ,"$" =>Shape ,"|:"=>Transpose , 90 | "#" =>Tally ,"[" =>Same ,"]" =>Same , 91 | ">:"=>Inc, _=>r!(None)})}} 92 | impl D {fn new(s:&str)->O {use D::*; Some(match s{"+" =>Plus ,"*" =>Mul ,"[" =>Left , 93 | "]" =>Right , _=>r!(None)})}} 94 | impl Ym{fn new(s:&str)->O{use Ym::*;Some(match s{"/" =>Insert,"\\"=>Prefix, _=>r!(None)})}} 95 | impl Yd{fn new(s:&str)->O{use Yd::*;Some(match s{"/" =>Table ,"\\"=>Infix , _=>r!(None)})}} 96 | #[cfg(test)]mod t{use super::*; 97 | macro_rules! t {($f:ident,$i:literal)=>{ 98 | #[test] fn $f()->R<()>{let(mut ts)=lex($i)?; let _=parse(&mut ts)?;ok!()}}} 99 | macro_rules! tf{($f:ident,$i:literal)=>{ 100 | #[test] #[should_panic]fn $f() {let(mut ts)=lex($i).unwrap();let _=parse(&mut ts).unwrap();}}} 101 | /*parsing unit tests; t!(..) asserts a success, while tf asserts a failure.*/ 102 | t!(parse_1x1,"1"); t!(parse_1x3,"1 2 3"); 103 | t!(parse_tally_1,"# 1"); t!(parse_tally_1x3,"# 1 2 3"); 104 | tf!(parse_tally_as_dyad_fails,"1 # 2"); tf!(parse_tally_with_no_operand, "#"); 105 | tf!(parse_idot_as_dyad_fails,"1 # 2"); tf!(parse_idot_with_no_operand, "i."); 106 | t!(parse_idot_1,"i. 1"); t!(parse_idot_1x2,"i. 4 3"); 107 | t!(parse_1plus2,"1 + 2"); t!(parse_1x3_times_1x3,"1 2 3 * 4 5 6"); 108 | t!(parse_tally_tally_1x3,"# # 1 2 3"); t!(parse_symbol,"a"); 109 | t!(parse_symbol_plus_symbol,"a + b"); t!(parse_tally_symbol,"# a"); 110 | t!(parse_symbol_times_symbol,"a * b"); t!(parse_tally_tally_symbol,"# # a"); 111 | tf!(parse_bad_symbol_literal,"a * b 1"); tf!(parse_tally_tally_symbol_symbol,"# # a b"); 112 | t!(assign_symbol_scalar,"a =: 1"); t!(assign_symbol_slice,"a =: 1 2 3"); 113 | t!(assign_symbol_idot,"a =: i. 2 3"); t!(parse_monad_then_dyad,"1 + # 1 2 3"); 114 | t!(assign_symbol_slice_plus_slice,"a =: 1 2 3 + 1 2 3"); t!(parse_empty,""); 115 | t!(parse_insert_add_to_matrix,"+ / i. 3 3"); t!(parse_prefix_of_sequence, "] \\ i. 3"); 116 | t!(parse_multiplication_table,"1 2 3 * / 1 2 3"); t!(parse_infixes_of_sequence,"4 ] \\ i. 10"); 117 | tf!(parse_no_verb_over_sequence_fails,"/ i. 3 3"); tf!(parse_no_verb_prefix_sequence_fails,"/ i. 3 3"); 118 | // NOTE: J will allow this, but first-class functions are not implemented here. 119 | tf!(parse_add_over_no_sequence_fails,"+ /"); tf!(parse_add_prefix_no_sequence_fails,"+ \\"); 120 | /* TODO: running sums should be supported */ // t!(parse_a_running_sum, "+ / \\ 1 2 3 4 5"); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/s.rs: -------------------------------------------------------------------------------- 1 | use super::*; use std::ops::Not; 2 | /**symbol*/ #[derive(PE,DBG,PO,Ord,Eq,CL)]pub struct SY(S); 3 | /**symbol table*/#[derive(Default)] pub struct ST{st:BM} 4 | 5 | /**symbol parsing*/mod syfs{use super::*; 6 | impl FS for SY{type Err = E;fn from_str(s:&str)->R{ 7 | let(sc)=s.chars().collect::>();let(sf)=sc.first().ok_or(err!("empty symbol"))?; 8 | if(sf.is_ascii_lowercase().not()){bail!("symbols must start with a-z")} 9 | let(sv)=|c:&char|c.is_ascii_lowercase()||c.is_ascii_digit()||*c=='_'; // validate 10 | if(sc.iter().all(sv).not()){bail!("symbols may only contain a-z, 0-9, or `_`")} 11 | Ok(SY(s.to_owned()))}} 12 | #[test] fn simple_symbol_succeeds() {is!(SY::from_str("abc") .is_ok())} 13 | #[test] fn underscore_symbol_succeeds() {is!(SY::from_str("abc_def").is_ok())} 14 | #[test] fn trailing_number_symbol_succeeds(){is!(SY::from_str("a1") .is_ok())} 15 | #[test] fn empty_symbol_fails() {is!(SY::from_str("") .is_err())} 16 | #[test] fn number_symbol_fails() {is!(SY::from_str("1") .is_err())} 17 | #[test] fn leading_number_symbol_fails() {is!(SY::from_str("1a") .is_err())} 18 | } 19 | 20 | impl ST{ 21 | pub fn get(&self,sy:&SY)->O<&A>{self.st.get(sy)} 22 | pub fn get_s(&self,sy:&str)->O<&A>{self.st.get(&sy.parse::().expect("valid symbol"))} 23 | pub fn insert(&mut self,sy:SY,a:A){self.st.insert(sy,a);} 24 | } 25 | -------------------------------------------------------------------------------- /src/x.rs: -------------------------------------------------------------------------------- 1 | /**a J interpreter fragment, implemented in Rust.*/ 2 | mod p;use{p::*,j::*,std::io::Write}; 3 | /// main interpreter entrypoint and event-loop. 4 | fn main()->R<()>{let mut st=ST::default(); // define symbol table 5 | let prompt =| |{print!(" ");std::io::stdout().flush()?;ok!()}; // (callback) print whitespace 6 | let read =|_ |{let mut l=S::new();stdin().read_line(&mut l)?;Ok(l)}; // (callback) read input 7 | let mut eval=|s:S|{eval(&s,&mut st)}; // (callback) read and evaluate once 8 | let print =|a:A|{println!("{a}")}; // (callback) print array 9 | loop{prompt().and_then(read).and_then(&mut eval)?.map(print);}; /* !!! main event loop !!! */ } 10 | -------------------------------------------------------------------------------- /sums/README.md: -------------------------------------------------------------------------------- 1 | # ∑ sum examples 2 | 3 | this directory contains programs that compute the sum of integers from 1 to 100 (inclusive). 4 | 5 | ###  running 6 | 7 | **sh** 8 | 9 | ```sh 10 | ./sum.sh 11 | ``` 12 | 13 | **C** 14 | 15 | ```sh 16 | gcc sum.c && ./a.out 17 | ``` 18 | 19 | **Rust** 20 | 21 | ```sh 22 | rustc sum.rs && ./sum 23 | ``` 24 | 25 | ```sh 26 | rustc sum2.rs && ./sum2 27 | ``` 28 | 29 | ```sh 30 | rustc sum3.rs && ./sum3 31 | ``` 32 | 33 | **Julia** 34 | 35 | ```sh 36 | julia sum.jl 37 | ``` 38 | 39 | **J** 40 | 41 | ```sh 42 | jconsole < sum.j 43 | ``` 44 | 45 | **K** 46 | 47 | ```sh 48 | k < sum.k 49 | ``` 50 | -------------------------------------------------------------------------------- /sums/sum.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int sum = 0; 5 | for (int i = 0; i <= 100; i++) 6 | { 7 | sum += i; 8 | } 9 | printf("%d", sum); 10 | } 11 | -------------------------------------------------------------------------------- /sums/sum.j: -------------------------------------------------------------------------------- 1 | + / 1 + i. 100 2 | -------------------------------------------------------------------------------- /sums/sum.jl: -------------------------------------------------------------------------------- 1 | sum = 0 2 | for i=1:100 3 | global sum = sum + i 4 | end 5 | print(sum) 6 | -------------------------------------------------------------------------------- /sums/sum.k: -------------------------------------------------------------------------------- 1 | +/1+!100 2 | -------------------------------------------------------------------------------- /sums/sum.r: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cratelyn/j/214ec8df936b80f394758bd516dcbcf423f23a76/sums/sum.r -------------------------------------------------------------------------------- /sums/sum.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut sum = 0; 3 | for i in 1..=100 { 4 | sum += i; 5 | } 6 | println!("{sum}"); 7 | } 8 | -------------------------------------------------------------------------------- /sums/sum.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | SUM=0 3 | for i in $(seq 100); 4 | do 5 | SUM=$(expr $SUM + $i) 6 | done 7 | echo $SUM 8 | -------------------------------------------------------------------------------- /sums/sum2.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let sum = (1..=100).fold(0, std::ops::Add::add); 3 | println!("{sum}"); 4 | } 5 | -------------------------------------------------------------------------------- /sums/sum3.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let sum: u32 = (1..=100).sum(); 3 | println!("{sum}"); 4 | } 5 | -------------------------------------------------------------------------------- /tests/t.rs: -------------------------------------------------------------------------------- 1 | #![allow(dead_code,unused_variables,unreachable_code,unused_imports,unused_parens)] 2 | #[path="../src/p.rs"]mod p; use{j::*,p::*,assert_eq as eq,assert_ne as neq,assert as is}; 3 | /**test helper: evaluate with empty symbol table*/fn eval_s(i:&str)->R{eval(i,&mut ST::default()).map(|i|i.unwrap())} 4 | #[cfg(test)]mod add{use super::*; 5 | #[test]fn add_two_consts()->R<()>{ 6 | let(a@A{m:1,n:1,..})=eval_s("1 + 2")? else{bail!("bad dims")};eq!(a.as_i()?,3);ok!()} 7 | #[test]fn add_const_to_arr()->R<()>{ 8 | let(a@A{m:1,n:3,..})=eval_s("1 + 1 2 3")? else{bail!("bad dims")};eq!(a.as_slice()?,&[2,3,4]);ok!()} 9 | #[test]fn add_arr_to_const()->R<()>{ 10 | let(a@A{m:1,n:3,..})=eval_s("1 2 3 + 1")? else{bail!("bad dims")};eq!(a.as_slice()?,&[2,3,4]);ok!()} 11 | #[test]fn add_arr_to_arr()->R<()>{ 12 | let(a@A{m:1,n:3,..})=eval_s("1 2 3 + 4 5 6")? else{bail!("bad dims")};eq!(a.as_slice()?,&[5,7,9]);ok!()} 13 | #[test]fn add_arr_to_rotated_matrix()->R<()>{ 14 | let(a@A{m:3,n:2,..})=eval_s("1 2 3 + i. 3 2")? else{bail!("bad dims")};eq!(a.into_matrix()?,&[&[1,2],&[4,5],&[7,8]]);ok!()} 15 | #[test]fn add_slice_to_rotated_slice()->R<()>{ 16 | let(a@A{m:4,n:1,..})=eval_s("1 2 3 4 + i. 4 1")? else{bail!("bad dims")};eq!(a.into_matrix()?,&[&[1],&[3],&[5],&[7]]);ok!()} 17 | #[test]fn other_add_slice_to_rotated_slice_is_length_error()->R<()>{is!(eval_s("i. 4 1 + 1 2 3 4").is_err());ok!()} 18 | } #[cfg(test)]mod increment{use super::*; 19 | #[test]fn increment_scalar()->R<()>{let(i)=eval_s(">: 1")?; eq!(i.as_i()?, 2); ok!()} 20 | #[test]fn increment_slice ()->R<()>{let(i)=eval_s(">: 1 2 3")?; eq!(i.as_slice()?, &[2,3,4]); ok!()} 21 | #[test]fn increment_matrix()->R<()>{let(i)=eval_s(">: i. 2 2")?;eq!(i.into_matrix()?,&[&[1,2],&[3,4]]);ok!()} 22 | } #[cfg(test)]mod tally{use super::*; 23 | macro_rules! t{($f:ident,$i:literal,$o:literal)=>{ 24 | #[test]fn $f()->R<()>{let(a@A{m:1,n:1,..})=eval_s($i)? else{bail!("bad dims")};eq!(a.as_slice()?,&[$o]);ok!()}}} 25 | t!(tally_scalar,"# 1",1);t!(tally_1x3,"# 1 2 3",3);t!(tally_3x3,"# i. 3 3",9); 26 | } #[cfg(test)]mod idot{use super::*; 27 | #[test]fn idot_3()->R<()>{let(a)=eval_s("i. 3")?;eq!(a.m,1);eq!(a.n,3);eq!(a.as_slice()?,&[0,1,2]);ok!()} 28 | #[test]fn idot_2_3()->R<()>{let(a)=eval_s("i. 2 3")?;eq!(a.m,2);eq!(a.n,3);let o:&[&[I]]=&[&[0,1,2],&[3,4,5]]; 29 | eq!(a.into_matrix()?,o);eq!(a,o);ok!()} 30 | #[test]fn idot_3_2()->R<()>{let(a)=eval_s("i. 3 2")?;eq!(a.m,3);eq!(a.n,2);let o:&[&[I]]=&[&[0,1],&[2,3],&[4,5]]; 31 | eq!(a.into_matrix()?,o);eq!(a,o);ok!()} 32 | } #[cfg(test)]mod shape{use super::*; 33 | #[test]fn shape_idot_2_3()->R<()>{let(a)=eval_s("$ i. 2 3")?;eq!(a.m,1);eq!(a.n,2); 34 | eq!(a.get(1,1)?,2);eq!(a.get(1,2)?,3);ok!()} 35 | #[test]fn shape_idot_3_2()->R<()>{let(a)=eval_s("$ i. 3 2")?;eq!(a.m,1);eq!(a.n,2); 36 | eq!(a.get(1,1)?,3);eq!(a.get(1,2)?,2);ok!()} 37 | } #[cfg(test)]mod trans{use super::*; 38 | #[test]fn trans_scalar()->R<()>{let(a)=eval_s("|: 3")?;eq!(a.m,1);eq!(a.n,1); 39 | eq!(a.get(1,1)?,3);ok!()} 40 | #[test]fn trans_idot_2_3()->R<()>{let(a)=eval_s("|: i. 2 3")?;eq!(a.m,3);eq!(a.n,2); 41 | let o:&[&[I]]=&[&[0,3],&[1,4],&[2,5]];eq!(a.into_matrix()?,o);eq!(a,o);ok!()} 42 | } #[cfg(test)]mod mult{use super::*; 43 | #[test]fn mult_two_scalars()->R<()>{let(a)=eval_s("2 * 3")?;let(i)=a.as_i()?;eq!(i,6);ok!()} 44 | #[test]fn mult_slice_by_scalar()->R<()>{let(a)=eval_s("1 2 3 * 3")?;eq!(a.as_slice()?,&[3,6,9]);ok!()} 45 | #[test]fn mult_scalar_by_slice()->R<()>{let(a)=eval_s("3 * 1 2 3")?;eq!(a.as_slice()?,&[3,6,9]);ok!()} 46 | #[test]fn mult_slice_by_slice()->R<()>{let(a)=eval_s("2 4 6 * 1 2 3")?;eq!(a.as_slice()?,&[2,8,18]);ok!()} 47 | #[test]fn mult_slice_by_rotated_slice()->R<()>{let(a@A{m:3,n:2,..})=eval_s("1 2 3 * i. 3 2")? else{bail!("bad dims")}; 48 | eq!(a.into_matrix()?,&[&[0,1],&[4,6],&[12,15]]);ok!()} 49 | #[test]fn mult_slice_to_rotated_slice()->R<()>{ 50 | let(a@A{m:4,n:1,..})=eval_s("1 2 3 4 * i. 4 1")? else{bail!("bad dims")};eq!(a.into_matrix()?,&[&[0],&[2],&[6],&[12]]);ok!()} 51 | } #[cfg(test)]mod left_and_right{use super::*; 52 | #[test]fn left_same_scalar() ->R<()>{let(a)=eval_s("[ 1")?; eq!(a.as_i()?,1); ok!()} 53 | #[test]fn left_same_slice() ->R<()>{let(a)=eval_s("[ 1 2 3")?; eq!(a.as_slice()?,&[1,2,3]);ok!()} 54 | #[test]fn right_same_scalar()->R<()>{let(a)=eval_s("] 1")?; eq!(a.as_i()?,1); ok!()} 55 | #[test]fn right_same_slice() ->R<()>{let(a)=eval_s("] 1 2 3")?; eq!(a.as_slice()?,&[1,2,3]);ok!()} 56 | #[test]fn left_dyad() ->R<()>{let(a)=eval_s("1 [ 2")?; eq!(a.as_i()?,1); ok!()} 57 | #[test]fn right_dyad() ->R<()>{let(a)=eval_s("1 ] 2")?; eq!(a.as_i()?,2); ok!()} 58 | #[test]fn left_dyad_other() ->R<()>{let(a)=eval_s("1 [ 2 3 4")?; eq!(a.as_i()?,1); ok!()} 59 | #[test]fn right_dyad_other() ->R<()>{let(a)=eval_s("1 ] 2 3 4")?; eq!(a.as_slice()?,&[2,3,4]);ok!()} 60 | #[test]fn left_dyad_does_not_rotate_slice()->R<()>{ 61 | /*NB: other operators like + or * may rotate the left-hand argument to fit. [ does not. */ 62 | let(a)=eval_s("1 2 3 4 [ i. 4 1")?;eq!(a.as_slice()?,&[1,2,3,4]);ok!()} 63 | } #[cfg(test)]mod symbol_assignment{use super::*; 64 | #[test]fn assign_and_get_i()->R<()>{let(mut st)=ST::default();let(a)=eval("a =: 3",&mut st)?; 65 | eq!(st.get_s("a").unwrap().as_i().unwrap(),3);ok!()} 66 | #[test]fn assign_and_get_slice()->R<()>{let(mut st)=ST::default();let(a)=eval("a =: 3 2 1",&mut st)?; 67 | eq!(st.get_s("a").unwrap().as_slice().unwrap(),&[3,2,1]);ok!()} 68 | #[test]fn assign_and_get_expr()->R<()>{let(mut st)=ST::default();let(a)=eval("a =: 1 3 + 2 4",&mut st)?; 69 | eq!(st.get_s("a").unwrap().as_slice().unwrap(),&[3,7]);ok!()} 70 | #[test]fn assign_and_eval_slice()->R<()>{let(mut st)=ST::default();let(eval_)=|s|eval(s,&mut st); 71 | let(mut i)=["a =: 3 2 1","a"].into_iter().map(eval_); is!(i.next().unwrap()?.is_none()); 72 | eq!(i.next().unwrap()?.unwrap().as_slice()?,&[3,2,1]); ok!()} 73 | #[test]fn assign_and_eval_expr()->R<()>{let(mut st)=ST::default();let(eval_)=|s|eval(s,&mut st); 74 | let(mut i)=["a =: >: i. 5","i =: 3","i ] \\ a"].into_iter().map(eval_); 75 | is!(i.next().unwrap()?.is_none()); is!(i.next().unwrap()?.is_none()); 76 | eq!(i.next().unwrap()?.unwrap().into_matrix()?,&[&[1,2,3],&[2,3,4],&[3,4,5]]); ok!()} 77 | } #[cfg(test)]mod misc{use super::*; 78 | #[test]fn empty_statement_evaluates_to_none()->R<()>{is!(eval("",&mut ST::default())?.is_none());ok!()} 79 | #[test]fn slice_times_transposed_idot_2_3()->R<()>{ 80 | let(a)=eval_s("1 2 3 * |: i. 2 3")?;eq!(a.into_matrix()?,&[&[0,3],&[2,8],&[6,15]]);ok!()} 81 | } #[cfg(test)]mod display{use super::*; 82 | #[test]fn display_scalar()->R<()>{let(a)=A::from_i(666)?;eq!(a.to_string(),"666\n");ok!()} 83 | #[test]fn display_slice()->R<()>{let a:&[I]=&[7,8,9];let a=A::try_from(a)?;eq!(a.to_string(),"7 8 9\n");ok!()} 84 | #[test]fn display_matrix()->R<()>{let(a)=eval_s("i. 3 3")?;eq!(a.to_string(),"0 1 2\n3 4 5\n6 7 8\n");ok!()} 85 | } #[cfg(test)]mod adverb{use super::*; 86 | // === monadic / "insert" adverb 87 | #[test]fn insert_sum_one_number()->R<()>{let(a)=eval_s("+ / 1")?;let(i)=a.as_i()?;eq!(i,1);ok!()} 88 | #[test]fn insert_sum_two_numbers()->R<()>{let(a)=eval_s("+ / 1 8")?;let(i)=a.as_i()?;eq!(i,9);ok!()} 89 | #[test]fn insert_sum_a_sequence()->R<()>{let(a)=eval_s("+ / i. 4")?;let(i)=a.as_i()?;eq!(i,6);ok!()} 90 | #[test]fn insert_sum_a_shifted_sequence()->R<()>{let(a)=eval_s("+ / 1 + i. 4")?;let(i)=a.as_i()?;eq!(i,10);ok!()} 91 | #[test]fn insert_product_of_a_sequence()->R<()>{let(a)=eval_s("* / i. 3")?;let(i)=a.as_i()?;eq!(i,0);ok!()} 92 | #[test]fn insert_product_of_a_shifted_sequence()->R<()>{let(a)=eval_s("* / 2 + i. 3")?;let(i)=a.as_i()?;eq!(i,24);ok!()} 93 | // === monadic \ "prefix" adverb 94 | #[test]fn prefix_of_scalar()->R<()>{let(a)=eval_s("] \\ 1")?;let(i)=a.as_i()?;eq!(i,1);ok!()} 95 | #[test]fn prefix_of_slice() ->R<()>{let(a)=eval_s("] \\ 1 2 3")?;eq!(a.into_matrix()?,&[&[1,0,0], 96 | &[1,2,0], 97 | &[1,2,3],]);ok!()} 98 | #[test]fn prefix_of_slice_2()->R<()>{let(a)=eval_s("+ \\ 1 2 3")?;eq!(a.into_matrix()?,&[&[1,0,0], 99 | &[1,2,0], 100 | &[1,2,3],]);ok!()} 101 | #[test]fn prefix_of_slice_3()->R<()>{let(a)=eval_s("* \\ 1 2 3")?;eq!(a.into_matrix()?,&[&[1,0,0], 102 | &[1,1,0], 103 | &[1,1,1],]);ok!()} 104 | // === dyadic / "table" adverb 105 | #[test]fn table_of_scalars_plus()->R<()>{let(a)=eval_s("1 + / 1")?;eq!(a.as_i()?,2);ok!()} 106 | #[test]fn table_of_scalars_mult()->R<()>{let(a)=eval_s("1 * / 1")?;eq!(a.as_i()?,1);ok!()} 107 | #[test]fn table_of_scalar_plus_slice()->R<()>{let(a)=eval_s("1 + / 1 2 3")?;eq!(a.as_slice()?,&[2,3,4]);ok!()} 108 | #[test]fn table_of_two_slices_mult()->R<()>{let(a)=eval_s("1 2 3 * / 1 2 3")?;eq!(a.into_matrix()?,&[&[1,2,3], 109 | &[2,4,6], 110 | &[3,6,9]]); 111 | ok!()} 112 | #[test]fn table_of_two_diff_slices_mult()->R<()>{let(a)=eval_s("2 4 * / 1 2 3")?;eq!(a.into_matrix()?,&[&[2,4,6], 113 | &[4,8,12]]); 114 | ok!()} 115 | // === dyadic \ "infix" adverb 116 | #[test]fn infix_to_reshape_1()->R<()>{let(a)=eval_s("1 ] \\ 1 2 3")?;eq!(a.into_matrix()?,&[&[1], 117 | &[2], 118 | &[3]]); 119 | ok!()} 120 | #[test]fn infix_to_reshape_2()->R<()>{let(a)=eval_s("2 ] \\ 1 2 3")?;eq!(a.into_matrix()?,&[&[1,2], 121 | &[2,3]]); 122 | ok!()} 123 | #[test]fn infix_to_reshape_3()->R<()>{let(a)=eval_s("3 ] \\ 1 2 3 4")?;eq!(a.into_matrix()?,&[&[1,2,3], 124 | &[2,3,4]]); 125 | ok!()} 126 | } #[cfg(test)]mod adverb_fancy{use super::*; /*XXX: these are left unsolved for now*/ 127 | #[ignore] #[test]fn running_sum_of_a_sequence()->R<()>{let(a)=eval_s("+ / \\ 1 2 3 4 5")?; 128 | let(i)=a.as_slice()?;eq!(i,&[1,3,6,10,15]);ok!()} 129 | #[ignore] #[test]fn running_product_of_a_sequence()->R<()>{let(a)=eval_s("* / \\ 1 2 3 4 5")?; 130 | let(i)=a.as_slice()?;eq!(i,&[1,2,6,24,120]);ok!()} 131 | } 132 | --------------------------------------------------------------------------------