├── apl-life.fs ├── LICENSE.txt ├── apl-life-anno.fs └── README.md /apl-life.fs: -------------------------------------------------------------------------------- 1 | #! /usr/bin/gforth 2 | 3 | cr ." Available free space on the dictionary: " unused . unused Constant unused0 4 | cr ." Machine word size: " cell . 5 | 6 | \ 1. Arrays 7 | : shape @ ; 8 | : data cell+ @ ; 9 | : first data @ ; 10 | Create [1] here , here cell+ , 1 , 11 | defer size :noname shape first ; is size 12 | 13 | : array { data shape -- a } here shape , data , ; 14 | here 0 , [1] array Constant [0] 15 | here 1 , [0] array Constant [] 16 | : scalar { u -- a } here u , [] array ; 17 | : vector { data u -- a } data here u , [1] array array ; 18 | : new { u -- data u } here u cells allot u ; 19 | 20 | : end { a -- addr } a data a size cells + ; 21 | : (for) { a -- and data } a end a data ; 22 | : FOR POSTPONE (for) POSTPONE ?DO ; immediate 23 | : EACH POSTPONE cell POSTPONE +LOOP ; immediate 24 | 25 | : .a FOR i ? EACH ; 26 | : !a ( an .. a1 array -- ) FOR i ! EACH ; 27 | : >a ( an .. a1 u -- a ) new vector { a } a !a a ; 28 | : fill { w u -- a } u new vector { a } a FOR w i ! EACH a ; 29 | 30 | : number? abs 32767 <= ; 31 | : array? number? 0= ; 32 | : print { a -- } 33 | a array? IF ." [" a shape .a ." | " a FOR i @ recurse EACH ." ] " ELSE a . THEN ; 34 | 35 | : before { a n -- a' } a data n vector ; 36 | : after { a n -- a' } a data n cells + a size n - vector ; 37 | : slice { a from count -- a' } a from after count before ; 38 | 39 | \ 2. Currying and closures 40 | : literal, ( w -- ) POSTPONE literal ; 41 | : compile-curried, { w xt -- } w literal, xt compile, ; 42 | : curry { w xt -- xt' } :noname w xt compile-curried, POSTPONE ; ; 43 | : compose { xt2 xt1 -- xt' } :noname xt1 compile, xt2 compile, POSTPONE ; ; 44 | : flip ( xt -- xt' ) ['] swap compose ; 45 | 46 | : bind-addr { addr xt -- xt' } 47 | :noname 48 | addr ['] @ compile-curried, xt compile, addr ['] ! compile-curried, 49 | POSTPONE ; ; 50 | : bind { w xt -- xt' } here w , xt bind-addr ; 51 | 52 | \ 3. Higher-order collection functions 53 | : !+ { n addr -- addr' } n addr ! addr cell+ ; 54 | : @+ { addr -- n addr' } addr @ addr cell+ ; 55 | : iterator ( a -- xt' ) data ['] @+ bind ; 56 | : inserter ( a -- xt' ) data ['] !+ bind ; 57 | 58 | : iter { xt a -- } a FOR i @ xt execute EACH ; 59 | : construct ( u -- a' xt) new vector dup inserter ; 60 | : shape! ( a shape -- a) over ! ; 61 | : shape-as ( a other -- a ) shape shape! ; 62 | 63 | : map { a xt -- a' } a size construct xt compose a iter a shape-as ; 64 | : zip { al ar xt -- a' } 65 | al size construct xt compose al iterator compose ar iter al shape-as ; 66 | : inject { a xt zero -- w } here { accum } zero , accum xt bind-addr a iter accum @ ; 67 | : fold { a xt -- w } a 1 after xt a first inject ; 68 | : contains { a w -- f } a w ['] = curry map ['] or false inject ; 69 | 70 | :noname { a -- u } a [1] = IF 1 ELSE a shape ['] * 1 inject THEN ; is size 71 | 72 | : flat { a -- a' } a ['] size map ['] + fold construct ['] iter flip curry a iter ; 73 | : (product) { w xt al -- } w xt curry al iter ; 74 | : product { al ar xt -- a' } 75 | al size ar size * construct 76 | xt compose al ['] (product) curry curry ar iter 77 | al size ar size 2 >a shape! ; 78 | : rotate { a offset -- a' } offset a size mod { n } a n before a n after 2 >a flat ; 79 | : integers { u -- a } u construct { xt } u 0 ?DO i xt execute LOOP ; 80 | 81 | : second data cell+ @ ; 82 | : height shape first ; 83 | : width shape second ; 84 | : rows { a -- a' } 85 | a height integers a width ['] * curry map 86 | a a width ['] slice curry flip curry map ; 87 | 88 | \ 4. APL specific functions 89 | : size { a -- u } a array? IF a size ELSE 1 THEN ; 90 | : shape { a -- a' } a array? IF a shape ELSE [] THEN ; 91 | : wrap { a -- a' } a array? IF a scalar ELSE a THEN ; 92 | : unwrap { a -- a' } a array? IF a first ELSE a THEN ; 93 | 94 | : rank shape shape first ; 95 | : 'recurse latestxt literal, ; immediate 96 | : depth { a -- a' } a array? IF a 'recurse map ['] max 0 inject 1+ ELSE 0 THEN ; 97 | : scalar? rank 0= ; 98 | 99 | : ravel { a -- a' } a data a size vector ; 100 | : uperv ( a xt -- a' ) over number? IF execute ELSE 'recurse curry map THEN ; 101 | 102 | defer perv 103 | : both-numbers? { al ar -- f } al number? ar number? and ; 104 | : both-iterable? { al ar -- f } al array? ar array? and al rank ar rank = and ; 105 | : pairwise ( al ar xt -- a' ) ['] perv curry zip ; 106 | : left-iterable? { al ar -- f } al array? ar scalar? and ; 107 | : extend { al ar xt -- a' } al ar unwrap xt ['] perv curry curry map ; 108 | :noname { al ar xt -- a' } 109 | al ar both-numbers? IF al ar xt execute EXIT THEN 110 | al ar both-iterable? IF al ar xt pairwise EXIT THEN 111 | al ar left-iterable? 0= IF ar al xt flip ELSE al ar xt THEN extend ; 112 | is perv 113 | 114 | : perv-+ ['] + perv ; 115 | : perv-and ['] and perv ; 116 | : perv-or ['] or perv ; 117 | : perv-* ['] * perv ; 118 | : apl-= = 1 and ; : perv-= ['] apl-= perv ; 119 | 120 | : hrotate { a u -- a' } a rows u ['] rotate curry map flat a shape-as ; 121 | : vrotate { a u -- a' } a rows u rotate flat a shape-as ; 122 | : reduce ( a xt -- a' ) fold wrap ; 123 | : hreduce { a xt -- a' } a rows xt ['] reduce curry map ; 124 | : vreduce { a xt -- a' } a rows xt fold ; 125 | : vector? rank 1 = ; 126 | : hrotate { a u -- a' } a u a vector? IF rotate ELSE hrotate THEN ; 127 | : hreduce { a xt -- a' } a xt a vector? IF reduce ELSE hreduce THEN ; 128 | 129 | : inner-product { * + -- a' } * zip + reduce ; 130 | : apl-product { al * + ar -- } 131 | + ['] noop = IF al ar * product ELSE al ar * + inner-product THEN ; 132 | 133 | 0 0 0 0 0 0 134 | 0 0 1 0 0 0 135 | 0 0 0 1 0 0 136 | 0 1 1 1 0 0 137 | 0 0 0 0 0 0 138 | 0 0 0 0 0 0 36 >a Constant grid 139 | 6 6 2 >a grid ! 140 | 141 | : show { a -- } 142 | a array? 0= IF a . EXIT THEN 143 | a scalar? IF a unwrap recurse EXIT THEN 144 | a vector? IF a FOR i @ recurse EACH EXIT THEN 145 | 'recurse ['] cr compose a rows iter ; 146 | 147 | \ 5. APL to FORTH translator 148 | : ⍵ ['] @local0 ['] compile, ; 149 | : continue ( token -- ) dup number? IF literal, ELSE execute THEN ; 150 | defer open 151 | 152 | : subexpression? ['] open = ; 153 | : identifier? ['] compile, = ; 154 | : value? { t -- f } t number? t subexpression? or t identifier? or ; 155 | 156 | : strand ( .. -- u ) 0 BEGIN { t cnt } t value? WHILE t continue cnt 1+ REPEAT t cnt ; 157 | : value strand { size } size 1 > IF size ['] >a compile-curried, THEN ; 158 | 159 | : function-ref { t -- } literal, ; 160 | : operator { xt -- } function-ref value xt compile, continue ; 161 | : dyadic-op operator ; 162 | : monadic-op operator ; 163 | : function { t xt -- } 164 | t ['] dyadic-op = IF t xt literal, ELSE t value xt compile, THEN continue ; 165 | 166 | :noname value continue ; is open 167 | : close ; 168 | 169 | : apl: { xt -- } : xt literal, ['] function literal, POSTPONE ; ; 170 | wordlist Constant apl get-current apl set-current 171 | ' first apl: ↑ ' perv-or apl: ∨ ' perv-and apl: ∧ 172 | ' perv-= apl: = ' perv-+ apl: + ' ravel apl: , 173 | ' noop apl: ∘ ' vrotate apl: ⊖ ' hrotate apl: ⌽ 174 | ' wrap apl: ⊂ ' perv-* apl: × ' size apl: ≢ 175 | : / ['] hreduce ['] monadic-op ; 176 | : . ['] apl-product ['] dyadic-op ; 177 | ' close Constant ( 178 | ' open Constant ) 179 | set-current 180 | 181 | : ←{ apl >order ['] close POSTPONE [ ; immediate 182 | : } open previous ] ; immediate 183 | 184 | \ The Game of Life 185 | : life { _ } ←{ ↑ 1 ⍵ ∨ . ∧ 3 4 = + / , -1 0 1 ∘ . ⊖ -1 0 1 ∘ . ⌽ ⊂ ⍵ } ; 186 | 187 | cr ." Memory used by code: " unused0 unused - cell / . ." words" 188 | 189 | marker gc 190 | cr ." The glider:" grid show 191 | cr ." The glider after 4 steps:" grid life life life life show 192 | cr ." Free space on dictionary after a run: " unused . 193 | gc 194 | cr ." Free space on dictionary after gc: " unused . 195 | 196 | bye 197 | 198 | \ apl-life.fs, Conway's Game of Life in APL in FORTH 199 | \ Copyright (c) 2020 Alexander Serkov 200 | 201 | \ This program is free software; you can redistribute it and/or modify it under the terms of 202 | \ the GNU General Public License version 2 as published by the Free Software Foundation. 203 | \ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 204 | \ without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 205 | \ See the GNU General Public License for more details. 206 | 207 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /apl-life-anno.fs: -------------------------------------------------------------------------------- 1 | #! /usr/bin/gforth 2 | 3 | \ I love FORTH and hope to present reasons with this code. 4 | 5 | \ The original idea was to implement Conway's Game of Life as a one-liner in APL executed in FORTH. 6 | \ (APL is another weird-looking programming language). The goal is mostly reached, with few exceptions. 7 | \ Unary negation symbol ¯ not implemented. APL tokens must be whitespace-separated, as in FORTH. 8 | 9 | \ FORTH is a low-level language and has no type checking, structures, arrays, let alone higher-level 10 | \ constructs. Instead, it provides a direct access to its interpreter and compiler. This comes to be 11 | \ an extremely powerful tool. It allows us to quickly jump from raw bytes into a world of a problem 12 | \ domain. The code below contains an implementation of 13 | \ - arrays 14 | \ - currying and closures 15 | \ - higher-order functions for collections 16 | \ - APL specific function application rules, such as pervasion 17 | \ - APL to FORTH translator (up to extend required to execute Conway's Game of Life) 18 | \ All of that is done in ~200 LOC and tooks < 2.5K words of memory. 19 | 20 | \ For these who had never met FORTH before, "word" in FORTH stays for function and "cell" for machine 21 | \ word. FORTH has no syntax restrictions: code is nothing but a stream of whitespace-separated words. 22 | \ FORTH is interactive: the code below is not only a complete program but also a history of a 23 | \ development session. 24 | 25 | \ A coding style is affected by an intention to avoid stack manipulation words. Locals are mostly used 26 | \ instead. Hope this might improve readability for people unfamiliar with FORTH. 27 | 28 | \ This code is written in gforth and contains Unicode symbols. 29 | 30 | \ References 31 | \ Conway's Game of Life https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life 32 | \ Conway's Game of Life in APL in Ruby https://zverok.github.io/blog/2020-05-16-ruby-as-apl.html 33 | \ APL programming language https://en.wikipedia.org/wiki/APL_(programming_language) 34 | \ John Scholes' Conway's Game of Life in APL https://aplwiki.com/wiki/John_Scholes%27_Conway%27s_Game_of_Life 35 | \ online APL playground https://tryapl.org/ 36 | \ FORTH programming language https://en.wikipedia.org/wiki/Forth_(programming_language) 37 | \ gforth docs https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/ 38 | 39 | cr ." Available free space on the dictionary: " unused . unused Constant unused0 40 | cr ." Machine word size: " cell . 41 | 42 | \ 1. Arrays 43 | 44 | \ First we have to implement arrays. APL arrays are multi-dimensional and support nesting which is an 45 | \ unrelated concept (a scalar is a 0-dimensional array, a vector is 1-dimensional, and matrix is 46 | \ 2-dimensional, and a vector of vectors is not a matrix). 47 | 48 | \ The main idea of the implementation provided below is the fact that array's shape is itself an array, 49 | \ so any array can be represented as a reference to another array and a reference to raw data. 50 | \ The FORTH word for dereferencing is "@" and for incrementing a pointer by one machine word is "cell+". 51 | 52 | \ Hereafter non-indented and single-idented lines contain the main program, while double-idented lines 53 | \ contain examples and tests explaining what's going on, and these can be omitted. We will write code 54 | \ in tiny steps and test every line just next to it. Sometimes we will first try things in interpreter 55 | \ mode and then wrap a code in a word definition. 56 | 57 | : shape @ ; 58 | : data cell+ @ ; 59 | : first data @ ; 60 | 61 | \ We have no function for array creation right now, but as the whole thing is a matter of convention, 62 | \ we can create the first array manually. Anywhere in a memory, suppose at address PTR, we will put a 63 | \ triplet [PTR; PTR+2; 1], and according to the definition above (the words "shape", "data" and 64 | \ "first"), this triplet can be understood as a 1-dimensional array with a single element, the 1. 65 | \ A triplet [1; PTR; PTR-1] would also do. 66 | 67 | \ In the line below, there are "Create", "here", and "," some of a most frequently used FORTH words. 68 | \ There is a memory area called Dictionary hosting FORTH words and other program data. The Dictionary 69 | \ is organized as a stack, so is filled continuously and incrementally. "here" is a pointer to free 70 | \ space on top of the Dictionary. "," (comma) writes a machine word from the data stack to the 71 | \ Dictionary and increments value of "here". "Create" introduces a new word (whatever is to the right 72 | \ of it) whose meaning is the value of "here" at the moment of the definition). 73 | 74 | \ So the line below states the following: 75 | \ Create [1] let the current value of "here" be called [1]. 76 | \ here put the value of "here" on the stack. 77 | \ , write the value from the stack to "here"; increment "here". 78 | \ here put the value of "here" on the stack (now "here" is [1] + 1 machine word). 79 | \ cell+ increment the value on the stack by 1 machine word. 80 | \ , write the value from the stack to "here"; increment "here". 81 | \ 1 put 1 on the stack. 82 | \ , write the value from the stack to "here". 83 | \ Thus we have created the [PTR; PTR+2; 1] triplet and assign it a name, [1]. 84 | 85 | Create [1] here , here cell+ , 1 , 86 | \ We can immediately examine this array with our accessor words: 87 | cr [1] . \ PTR (some integer value of a pointer) 88 | cr [1] shape . \ PTR (shape of [1] is [1]) 89 | cr [1] data . \ PTR+2 90 | cr [1] first . \ 1 91 | 92 | \ Note the [1] is the only array whose shape is equal to the array itself, so it's naturally the only 93 | \ choice for an array to be created first. 94 | 95 | \ The very important property of an array is its size. It is not very clear what is "size" in a general 96 | \ case but what we need first is a size of memory chunk to allocate for array items. A scalar requires 97 | \ 1 memory cell, a vector as many cells as there are items, and a matrix a product of rows and columns. 98 | \ Right now we have no functions to iterate over shape, so let's define "size" for the simplest case of 99 | \ 1-dimensional arrays, like this: 100 | : size shape first ; 101 | 102 | \ FORTH allows us to redefine any word, and a new behavior hides an old one. But a words already 103 | \ compiled still refer to the old implementation. In case we want not to hide but retroactively change 104 | \ the meaning of a word, we have to declare at as "deferred", i.e. linked dynamically. 105 | 106 | \ The definition of deferred "size" looks like this: 107 | defer size 108 | :noname shape first ; 109 | is size 110 | 111 | \ Here is a word to create new arrays at run-time: 112 | : array { data shape -- a } here shape , data , ; 113 | \ Without locals, this could be written as: 114 | : array ( data shape -- a ) here -rot , , ; 115 | \ Which is significantly shorter but not so explanatory. 116 | 117 | \ We can try it with following line: 118 | here 0 , [1] array Constant [0] 119 | \ Here we have first allocated a single cell of memory and saved 0 here (with a phrase "here 0 ,", 120 | \ which is readable as well as plain English); then we've provided the array shape, [1]; then called 121 | \ the constructor "array" and assigned a name "[0]". It is a one-dimensional array containing a single 122 | \ value, 0. 123 | cr [0] . \ some pointer 124 | cr [0] shape . \ PTR (the pointer to [1]) 125 | cr [0] first . \ 0 126 | cr [0] size . \ 1 127 | 128 | \ An empty array is even simplier, as it does not need allocated data so we can use 0 in place of data 129 | \ pointer: 130 | 0 [0] array Constant [] 131 | cr [] . \ pointer to [] 132 | cr [] shape . \ pointer to [0] 133 | cr [] size . \ 0 134 | \ But it is more convenient to reuse the data pointer of [1], so our (still incomplete) definition 135 | \ of "size" will work properly: 136 | here 1 , [0] array Constant [] 137 | cr [] first . \ 1 138 | 139 | \ Let's define some more convenient constructors. 140 | \ Scalar is a zero-dimensional array (i.e., its shape is an empty vector): 141 | : scalar { u -- a } here u , [] array ; 142 | 143 | \ The following line creates a scalar with value "101": 144 | 101 scalar Constant tmp 145 | cr tmp shape . \ pointer to [] 146 | cr tmp first . \ 101 147 | cr tmp size . \ 1 148 | 149 | \ Vector is a one-dimensional array. Its shape is a single-element vector. A vector constructor accepts 150 | \ a pointer to a pre-allocated data area and a size. It creates a shape vector ("here u , [1] array") 151 | \ and then calls "array": 152 | : vector { data u -- a } data here u , [1] array array ; 153 | 154 | \ To see it working, we have to manually allocate data here and store some values: 155 | here 103 , 107 , 156 | \ And then we call a vector constructor (the value of "here" is already on the stack): 157 | 2 vector Constant tmp 158 | cr tmp size . \ 2 159 | cr tmp first . \ 103 160 | cr tmp data cell+ @ . \ 107 161 | 162 | \ Here is an utility word that allocates a data area for a given number of elements: 163 | : new { u -- data u } here u cells allot u ; 164 | 165 | \ Examine it like this: 166 | 5 new vector Constant tmp 167 | cr tmp size . \ 5 168 | cr tmp first . \ (some value from an unassigned memory cell) 169 | \ The vector we've just created is ready but not populated, we can assign values with common memory 170 | \ accessing words: 171 | 109 tmp data ! 172 | cr tmp first . \ 109 173 | 174 | \ Now we can define how to iterate over items, that is, to implement the "for each" loop. 175 | 176 | \ There is several loop words in FORTH, such as "DO", "?DO", "LOOP", "+LOOP", and "I", which can be 177 | \ used like this: 178 | cr 5 0 [DO] [i] . [LOOP] \ 0 1 2 3 4 179 | cr 5 0 [?DO] [i] . 2 [+LOOP] \ 0 2 4 180 | 181 | \ To iterate over our array items, we need to loop from data start to data end in one-machine-word 182 | \ steps. Here is a word to get a data end: 183 | : end { a -- addr } a data a size cells + ; 184 | \ And here is a word to put on the stack both data end and data start, in this order: 185 | : (for) { a -- and data } a end a data ; 186 | \ Test it by creating two-element vector and definiting a printing function: 187 | here 113 , 127 , 2 vector Constant tmp 188 | : fn (for) ?DO i ? cell +LOOP ; 189 | cr tmp fn \ 113 127 190 | 191 | \ This is not very readable, and is error-prone since we can easily forget the word "cell" before 192 | \ "+LOOP", which would break the pointer arithmetic. But we can easily enhance the language syntax: 193 | : FOR POSTPONE (for) POSTPONE ?DO ; immediate 194 | : EACH POSTPONE cell POSTPONE +LOOP ; immediate 195 | 196 | \ And use it like this: 197 | : .a FOR i ? EACH ; 198 | 199 | cr tmp .a \ 113 127 200 | 201 | \ What's going on here needs a more elaborate explanation. "immediate" words are words executed at 202 | \ compile-time (contrary to words executed at run-time). The word "POSTPONE" says the following word 203 | \ (e.g., "(for)") will not be normally executed when "FOR" executed but instead will be compiled into 204 | \ the body of a word being defined during execution of "FOR", which is in our case ".a". So when 205 | \ compiled the code of ".a" is exactly equivalent to this of "print". This can be seen with decompiler: 206 | cr see fn \ : fn (some code follows) 207 | cr see .a \ : .a (the same code) 208 | 209 | \ You may see this as a sort of macro. With two lines of code, we've extended language syntax with 210 | \ the new construction, "for each" loop working with our arrays. You may want to implement it in your 211 | \ language. 212 | 213 | \ Here is a word to populate an existing array from the stack: 214 | : !a ( an .. a1 array -- ) FOR i ! EACH ; 215 | 216 | \ And a word to create an array and populate it from the stack: 217 | : >a ( an .. a1 u -- a ) new vector { a } a !a a ; 218 | 219 | 4 3 2 1 4 >a Constant 1_2_3_4 220 | cr 1_2_3_4 .a \ 1 2 3 4 221 | \ Note the reversed element order. 222 | 223 | \ A word to create an array and fill it with single value: 224 | : fill { w u -- a } u new vector { a } a FOR w i ! EACH a ; 225 | cr 5 4 fill .a \ 5 5 5 5 226 | 227 | \ Some not-that-pretty-printer supporting recursive/nested arrays: 228 | : number? abs 32767 <= ; 229 | : array? number? 0= ; 230 | : print { a -- } 231 | a array? IF ." [" a shape .a ." | " a FOR i @ recurse EACH ." ] " ELSE a . THEN ; 232 | \ Here I assume our arrays will host only short ints and pointers to other arrays, and its ranges 233 | \ do not overlap. 234 | 235 | cr 131 print \ 131 236 | cr 131 scalar print \ [| 131] 237 | cr 131 1 >a print \ [1| 131] 238 | cr 1_2_3_4 print \ [4| 1 2 3 4] 239 | cr 4 3 2 2 >a 1 3 >a print \ [3| 1 [2| 2 3] 4] 240 | 241 | \ Following functions perform partitioning/slicing, we will need it later. 242 | \ Note the data is not copied here, but pointers only. 243 | : before { a n -- a' } a data n vector ; 244 | : after { a n -- a' } a data n cells + a size n - vector ; 245 | : slice { a from count -- a' } a from after count before ; 246 | cr 1_2_3_4 2 before .a \ 1 2 247 | cr 1_2_3_4 2 after .a \ 3 4 248 | cr 1_2_3_4 1 2 slice .a \ 2 3 249 | 250 | 251 | 252 | 253 | \ 2. Currying and closures 254 | 255 | \ There is nothing related to functional programming in FORTH. But as we know the FP is a powerful 256 | \ paradigm we will implement some of its features here. Namely: currying, runtime function composition, 257 | \ and closures. 258 | 259 | \ Currying is implemented by binding together a function and its last argument. 260 | 261 | \ Here is how such binding looks like if done at compile time: 262 | : 10+ 10 + ; 263 | cr see 10+ \ : 10+ 10 + ; 264 | cr 9 10+ . \ 19 265 | \ Basically, this is nothing but creating a new short function. The main point is that we want this 266 | \ to happens at run-time, not at compile-time. 267 | 268 | \ First, our run-time-created function should be unnamed, like this: 269 | :noname 10 + ; 270 | cr xt-see \ noname: 10 + ; 271 | 272 | \ Second, the argument value and the function value has to be provided at run-time. Here we will 273 | \ rewrite the previous definition, separating run-time-provided values from the rest of the function 274 | \ body: 275 | :noname [ 10 ] literal [ ' + compile, ] ; 276 | cr xt-see \ noname: 10 + ; 277 | \ The result is equivalent but the source looks differently. The words [ and ] switch the FORTH state 278 | \ from compilation to interpretation and back. So the phrase above could be read like: 279 | \ :noname start the definition of a new unnamed word 280 | \ [ 10 ] at compile-time, put 10 on the stack 281 | \ literal what is on the stack at compile-time gets compiled into 282 | \ the unnamed word we are currently compiling 283 | \ [ ' + at compile-time, put the function + on the stack 284 | \ compile, at compile-time, compile what is on the stack 285 | \ into the unnamed word we are currenly compiling 286 | \ ] ...go back to compilation state 287 | \ ; end of the word 288 | \ As you can see with xt-see, this word is decompiled extacly as the previous one. 289 | 290 | \ The word "'" (tick) is one of few so-called parsing words. It takes an input not from the data stack 291 | \ but from the input stream. In the code above, the tick consumes the following "+" from the input 292 | \ stream, so instead of execute "+", the interpreter put reference to "+" on the stack. 293 | 294 | \ Values 10 and ' + could be moved out to some variables: 295 | 10 Value w 296 | ' + Value xt 297 | :noname [ w ] literal [ xt compile, ] ; 298 | cr xt-see \ noname: 10 + 299 | 300 | \ And the last step is to make it all to be performed at run-time. Keep in mind the run-time 301 | \ of "curry" is a compile-time of its derived unnamed word. 302 | : curry { w xt -- xt' } 303 | :noname w POSTPONE literal xt compile, POSTPONE ; 304 | ; 305 | \ What was previously done at compile-time ("w", "xt compile,") now is done at run-time, so not 306 | \ enclosed in [ ]. What must be done at run-time of the derived unnamed word is POSTPONEd. 307 | 308 | w xt curry 309 | cr xt-see \ noname: 10 + 310 | 11 ' - curry 311 | cr xt-see \ noname: 11 - 312 | \ It works! 313 | \ As our definition of "curry" is somewhat long, we will split into 3 words: 314 | : literal, ( w -- ) POSTPONE literal ; 315 | : compile-curried, { w xt -- } w literal, xt compile, ; 316 | : curry { w xt -- xt' } :noname w xt compile-curried, POSTPONE ; ; 317 | 318 | \ In the same way we implement a function composition: 319 | : compose { xt2 xt1 -- xt' } :noname xt1 compile, xt2 compile, POSTPONE ; ; 320 | \ Test it by composing the increment `1+` with the output '.'. 321 | cr ' . ' 1+ compose Constant tmp 322 | cr tmp xt-see \ noname : 1+ . ; 323 | cr 211 tmp execute \ 212 324 | 325 | \ In case we need to curry not the last but second-from-last argument, we can flip function arguments 326 | \ by composing it with the word "swap", and then bind the last argument as before: 327 | : flip ( xt -- xt' ) ['] swap compose ; 328 | \ Let's check it with the assymetrical two-argument function "divide": 329 | \ Divide by 10: 330 | 10 ' / curry Constant /10 331 | cr 30 /10 execute . \ 3 332 | \ Divide 10 by: 333 | 10 ' / flip curry Constant 10/ 334 | cr 5 10/ execute . \ 2 335 | 336 | \ Closures bind a function to a variable. As we don't use variables, we will use pointers, i.e. bind 337 | \ function directly to a memory cell. A bound function is an unnamed function which first reads a value 338 | \ from the cell, then executes a body of the target function, then writes a value back into the cell. 339 | : bind-addr { addr xt -- xt' } 340 | :noname 341 | addr ['] @ compile-curried, xt compile, addr ['] ! compile-curried, 342 | POSTPONE ; ; 343 | : bind { w xt -- xt' } here w , xt bind-addr ; 344 | 345 | \ "bind-addr" binds function to a provided memory cell. 346 | \ "bind" allocates a memory cell and writes an initial value here, then bounds. 347 | 348 | \ In the example below, we create a cell with a value "223" in it, then bind a function "1+" to it. 349 | \ The new function, referenced by "xt", will increment the value in the cell every time it is called. 350 | Create tmp 223 , 351 | tmp ' 1+ bind-addr Constant xt 352 | cr tmp ? \ 223 353 | cr xt execute tmp ? \ 224 354 | cr xt execute tmp ? \ 225 355 | 356 | \ Note: implemented this way, closures require a function to left on top of the stack a value 357 | \ semantically equivalent to a value on top of the stack at function start, i.e. the last argument 358 | \ value. In the example above, binding works as expected because "1+" has the required stack effect 359 | \ ( w -- w ). It will also work with "+": 360 | tmp ' + bind-addr Constant xt 361 | cr 100 xt execute tmp ? \ 325 362 | cr 200 xt execute tmp ? \ 525 363 | 364 | \ Words which don't follow this pattern must be wrapped accordingly. The "." word which is ( w -- ) 365 | \ need to be wrapped like this: 366 | : fn ( w -- w ) dup . ; 367 | tmp ' fn bind-addr Constant xt 368 | cr xt execute \ 525 369 | \ -- end of note. 370 | 371 | 372 | 373 | 374 | \ 3. Higher-order collection functions 375 | 376 | \ Now let's implement collection functions such as map. We already have a way to iterate over 377 | \ a collection (the for each loop), but this seems to be not enough, as some functions have to iterate 378 | \ over two or more collections simultaneously. We will implement another well-known solution called 379 | \ an iterator. Actually, the iterator's functionaly overlaps with this of the for each loop, so we 380 | \ would not need the for each if we have full-scale iterators. But we will implement only very basic 381 | \ iterators without any range checkings, and rely on loops for a counting. 382 | 383 | \ A simple iterator is a pointer that increases its value every time it is read. 384 | 385 | \ The reading word is "@", the writing is "!", and the pointer increment is "cell+". Here we define 386 | \ words for "read and increment pointer" and "write and increment pointer": 387 | : !+ { n addr -- addr' } n addr ! addr cell+ ; 388 | : @+ { addr -- n addr' } addr @ addr cell+ ; 389 | \ (By the way, it can be written much simpler without locals, but stack manipulation words make code 390 | \ look somewhat creepy, or at least cryptic: 391 | : !+ tuck ! cell+ ; 392 | : @+ dup @ swap cell+ ; 393 | 394 | \ Try it with the following code. Here we allocate two memory cells with values 101 and 103 and create 395 | \ a pointer "tmp" to the first. After the call to "107 tmp !+" the value 107 is written over the 101, 396 | \ and the incremented value of the pointer is left on the stack. After the next call, "109 swap !+", 397 | \ the value 109 is written over the 103. 398 | Create tmp 101 , 103 , 399 | cr tmp ? tmp cell+ ? \ 101 103 400 | cr tmp . \ some ptr 401 | 107 tmp !+ 402 | cr dup . \ ptr to next cell 403 | 109 swap !+ 404 | cr . \ ptr to yet next cell 405 | cr tmp ? tmp cell+ ? \ 107 109 406 | 407 | \ The iterator is made of "!+" or "@+" bound with a pointer, and the initial pointer value is the data 408 | \ pointer of the target array: 409 | 1_2_3_4 data ' @+ bind Constant tmp 410 | cr tmp execute . \ 1 411 | cr tmp execute . \ 2 412 | cr tmp execute . \ 3 413 | : iterator ( a -- xt' ) data ['] @+ bind ; 414 | : inserter ( a -- xt' ) data ['] !+ bind ; 415 | 416 | \ As we need something with counter to provide range checking, we'll wrap the for each loop into 417 | \ a functional-style iteration: let the word "iter" accept a function and an array and apply 418 | \ the function to every item: 419 | : iter { xt a -- } a FOR i @ xt execute EACH ; 420 | 421 | cr ' . 1_2_3_4 iter \ 1 2 3 4 422 | \ We could define a "clone" function like this: 423 | : clone { a -- a' } 424 | a size new vector { a' } 425 | a' inserter 426 | a iter 427 | a' ; 428 | cr 1_2_3_4 clone .a \ 1 2 3 4 429 | \ Since many of collection functions we need (map, zip, product...) follow the pattern 430 | \ "create array - create inserter - do something - return newly created array", we will extract 431 | \ the logic into a word: 432 | : construct { u -- a' xt } u new vector { a' } a' a' inserter ; 433 | \ The sequence "{ a' } a' a'" looks especially silly, as it just duplicates a value on the stack, so 434 | \ with your permission I'm going to use one of stack manipulation words, "DUP": 435 | : construct ( u -- a' xt) new vector dup inserter ; 436 | 437 | \ Finally, in the definition of the "clone" above, the resulting array is always a vector, while 438 | \ the function input can have some other shape. 439 | \ The word to change a shape of an existing array is trivial: 440 | : shape! ( shape a -- ) ! ; 441 | \ But it is more suitable for our needs to left the array on the stack: 442 | : shape! { a shape -- a } shape a ! a ; 443 | \ Or without locals: 444 | : shape! ( a shape -- a) over ! ; 445 | \ The word to copy shape from one array to another can looks like this: 446 | : shape-as ( a other -- a ) shape shape! ; 447 | 448 | \ So there are some basic collection functions. 449 | : map { a xt -- a' } a size construct xt compose a iter a shape-as ; 450 | : zip { al ar xt -- a' } 451 | al size construct xt compose al iterator compose ar iter al shape-as ; 452 | : inject { a xt zero -- w } here { accum } zero , accum xt bind-addr a iter accum @ ; 453 | : fold { a xt -- w } a 1 after xt a first inject ; 454 | : contains { a w -- f } a w ['] = curry map ['] or false inject ; 455 | \ Any function could be tested immediately: 456 | cr 1_2_3_4 ' 1+ map .a \ 2 3 4 5 457 | cr 1_2_3_4 1_2_3_4 ' + zip .a \ 2 4 6 8 458 | cr 1_2_3_4 ' + 10 inject . \ 20 459 | cr 1_2_3_4 ' + fold . \ 10 460 | cr 1_2_3_4 2 contains . \ -1 461 | cr 1_2_3_4 5 contains . \ 0 462 | 463 | \ Now we can provide the correct implementation for "size". Note we use "inject" and not "fold" because 464 | \ a shape of a scalar is an empty vector but its size is defined as 1. 465 | cr 2 3 2 >a ' * 1 inject . \ 6 466 | 467 | \ Also, we have to protect it from infinite recursion on [1]: 468 | :noname { a -- u } a [1] = IF 1 ELSE a shape ['] * 1 inject THEN ; is size 469 | 470 | \ Check it: 471 | cr [1] size . \ 1 472 | cr 1_2_3_4 size . \ 4 473 | 6 5 4 3 2 1 6 >a 3 2 2 >a shape! Constant _m2x3 474 | cr _m2x3 size . \ 6 475 | cr [] size . \ 0 476 | cr 1 [] array size . \ 1 477 | \ Note items of nested arrays doesn't count, as expected: 478 | cr 1_2_3_4 1_2_3_4 2 >a size . \ 2 479 | 480 | \ Some more collection functions, implemented just for purpose of Game of Life. 481 | 482 | \ "flat" accepts a homogeneous vector of vectors, and returns a new vector: 483 | : flat { a -- a' } a ['] size map ['] + fold construct ['] iter flip curry a iter ; 484 | cr 1_2_3_4 1_2_3_4 2 >a flat print \ [8| 1 2 3 4 1 2 3 4] 485 | 486 | \ "product" accepts two vectors and returns a matrix: 487 | : (product) { w xt al -- } w xt curry al iter ; 488 | : product { al ar xt -- a' } 489 | al size ar size * construct 490 | xt compose al ['] (product) curry curry ar iter 491 | al size ar size 2 >a shape! ; 492 | cr 1_2_3_4 20 10 2 >a ' + product print \ [2 4| 11 12 13 14 21 22 23 24] 493 | cr 20 10 2 >a 1_2_3_4 ' + product print \ [4 2| 11 21 12 22 13 23 14 24] 494 | 495 | \ "rotate" rotates element of a vector: 496 | : rotate { a offset -- a' } offset a size mod { n } a n before a n after 2 >a flat ; 497 | cr 1_2_3_4 1 rotate .a \ 2 3 4 1 498 | cr 1_2_3_4 -1 rotate .a \ 4 1 2 3 499 | 500 | \ "integers" is a constructor that creates a sequence from 0 to u-1: 501 | : integers { u -- a } u construct { xt } u 0 ?DO i xt execute LOOP ; 502 | cr 4 integers .a \ 0 1 2 3 503 | 504 | \ "rows" accepts a matrix and returns a vector of vectors: 505 | : second data cell+ @ ; 506 | : height shape first ; 507 | : width shape second ; 508 | : rows { a -- a' } 509 | a height integers a width ['] * curry map 510 | a a width ['] slice curry flip curry map ; 511 | cr _m2x3 print \ [2 3| 1 2 3 4 5 6] 512 | cr _m2x3 rows print \ [2| [3| 1 2 3 ] [3| 4 5 6]] 513 | 514 | 515 | 516 | 517 | \ 4. APL specific functions 518 | 519 | \ Here we get closer to the APL world. In APL, the array is a basic object. Any numeric value is 520 | \ a scalar an therefore an array (of rank 0). Every item of every array, unless it is a scalar 521 | \ containing a numeric value, is also an array. This is not true in our model. Our arrays can contain 522 | \ not only arrays (including scalars) but also naked numeric values, like this: 523 | cr 1_2_3_4 print \ [4| 1 2 3 4] 524 | \ While the array-only model would represent the same value as follows: 525 | cr 1_2_3_4 ' scalar map print \ [4| [| 1] [| 2] [| 3] [| 4]] 526 | 527 | \ Here we update some array functions to work properly with plain numbers. 528 | : size { a -- u } a array? IF a size ELSE 1 THEN ; 529 | : shape { a -- a' } a array? IF a shape ELSE [] THEN ; 530 | 531 | \ According to APL rules, we can wrap any array into a scalar, but a number wrapped in a scalar is 532 | \ equal to the number itself. 533 | : wrap { a -- a' } a array? IF a scalar ELSE a THEN ; 534 | : unwrap { a -- a' } a array? IF a first ELSE a THEN ; 535 | 536 | \ Here are definitions for basic array properties "rank" and "depth": 537 | : rank shape shape first ; 538 | : 'recurse latestxt literal, ; immediate 539 | : depth { a -- a' } a array? IF a 'recurse map ['] max 0 inject 1+ ELSE 0 THEN ; 540 | : scalar? rank 0= ; 541 | 542 | cr 1 wrap print \ 1 543 | cr [1] wrap print \ [| [1| 1]] 544 | cr 1 unwrap print \ 1 545 | cr 1 scalar unwrap print \ 1 546 | cr 1 rank . \ 0 547 | cr [1] scalar rank . \ 0 548 | cr [1] rank . \ 1 549 | cr _m2x3 rank . \ 2 550 | 551 | cr 1 depth . \ 0 552 | cr [1] depth . \ 1 553 | cr _m2x3 depth . \ 1 554 | cr [1] scalar depth . \ 2 555 | cr [1] scalar scalar depth . \ 3 556 | 557 | \ Conversion from an arbitrary-shaped array into a 1-dimensional vector: 558 | : ravel { a -- a' } a data a size vector ; 559 | 560 | \ One of APL features important for our task is the pervasive function application. If there is 561 | \ a function defined on scalars, such as +, it can be applied to arrays, and its behavior is 562 | \ to traverse thru array elements and apply to each. 563 | \ First, we implement the pervasive application of unary function: 564 | : uperv ( a xt -- a' ) over number? IF execute ELSE 'recurse curry map THEN ; 565 | 566 | cr 1 ' 1+ uperv print \ 2 567 | cr [1] ' 1+ uperv print \ [1| 2] 568 | cr 1_2_3_4 ' 1+ uperv print \ [4| 2 3 4 5] 569 | 4 3 2 2 >a 1 3 >a Constant tmp 570 | cr tmp ' 1+ uperv print \ [3| 2 [2| 3 4] 5] 571 | 572 | \ The binary pervasive application is a bit more complicated. It both arguments are arrays, 573 | \ the function is applied to corresponding pairs (as "zip"). If one argument is an array and another 574 | \ is a scalar, the scalar is "extended" as if it is an array of a required size. In the our case we 575 | \ don't have to create a new array representing this "extended" scalar but will curry the function 576 | \ with the scalar and then "map" over the array. 577 | 578 | \ The implementation going to take more than one word and contain a mutual recursion, so "defer": 579 | defer perv 580 | 581 | \ If both arguments are numbers, 582 | : both-numbers? { al ar -- f } al number? ar number? and ; 583 | \ then simply "execute", and this is our first runnable version of "perv": 584 | :noname { al ar xt -- a' } 585 | al ar both-numbers? IF al ar xt execute EXIT THEN 586 | s" not implemented yet" exception throw ; 587 | is perv 588 | 589 | cr 1 2 ' + perv print \ 3 590 | 591 | \ If both arguments can be iterated over, 592 | : both-iterable? { al ar -- f } al array? ar array? and al rank ar rank = and ; 593 | \ then zip: 594 | : pairwise ( al ar xt -- a' ) ['] perv curry zip ; 595 | \ Update the definition of "perv" to test it: 596 | :noname { al ar xt -- a' } 597 | al ar both-numbers? IF al ar xt execute EXIT THEN 598 | al ar both-iterable? IF al ar xt pairwise EXIT THEN 599 | s" not implemented yet" exception throw ; 600 | is perv 601 | 602 | cr 1_2_3_4 1_2_3_4 ' + perv print \ [4| 2 4 6 8] 603 | 604 | \ If the right argument is a scalar and the left is iterable, 605 | : left-iterable? { al ar -- f } al array? ar scalar? and ; 606 | \ then curry xt with the scalar and then map over the array: 607 | : extend { al ar xt -- a' } al ar unwrap xt ['] perv curry curry map ; 608 | \ Update the "perv": 609 | :noname { al ar xt -- a' } 610 | al ar both-numbers? IF al ar xt execute EXIT THEN 611 | al ar both-iterable? IF al ar xt pairwise EXIT THEN 612 | al ar left-iterable? IF al ar xt extend EXIT THEN 613 | s" not implemented yet" exception throw ; 614 | is perv 615 | 616 | cr 1_2_3_4 4 ' + perv print \ [4| 5 6 7 8] 617 | \ Finally, if the left argument is a scalar and the right is iterable, just swap the arguments and flip 618 | \ the "xt", then fall to "extend" as above. 619 | 620 | \ The complete code follows: 621 | :noname { al ar xt -- a' } 622 | al ar both-numbers? IF al ar xt execute EXIT THEN 623 | al ar both-iterable? IF al ar xt pairwise EXIT THEN 624 | al ar left-iterable? 0= IF ar al xt flip ELSE al ar xt THEN extend ; 625 | is perv 626 | 627 | \ Examine its behavior: 628 | cr 1 2 ' + perv print \ 3 629 | cr 1 1_2_3_4 ' + perv print \ [4| 2 3 4 5] 630 | cr 1 1_2_3_4 wrap ' + perv print \ [| [4| 2 3 4 5]] 631 | cr [1] 1_2_3_4 wrap ' + perv print \ [1| [4| 2 3 4 5]] 632 | cr 2 1 2 >a 1_2_3_4 wrap ' + perv print \ [2| [4| 2 3 4 5] [4| 3 4 5 6]] 633 | cr 1_2_3_4 1_2_3_4 ' + perv print \ [4| 2 4 6 8] 634 | cr 1_2_3_4 1_2_3_4 wrap ' + perv print \ [4| [4| 2 3 4 5] [4| 3 4 5 6] [4| 4 5 6 7] [4| 5 6 7 8]] 635 | cr [1] 2 ' + perv print \ [1| 3] 636 | cr 2 [1] ' + perv print \ [1| 3] 637 | cr [1] [1] ' + perv print \ [1| 2] 638 | cr 2 1 2 >a 1 ' + perv print \ [2| 2 3] 639 | cr 2 1 2 >a 4 3 2 >a ' + perv print \ [2| 4 6] 640 | cr 2 1 2 >a 4 3 2 >a wrap ' + perv print \ [2| [2| 4 5] [2| 5 6]] 641 | cr 2 1 2 >a wrap 4 3 2 >a wrap ' + perv print \ [| [2| 4 6]] 642 | cr 2 1 2 >a wrap 4 3 2 >a wrap wrap ' + perv print \ [| [2| [2| 4 5] [2| 5 6]]] 643 | cr 2 1 2 >a wrap 1 ' + perv print \ [| [2| 2 3]] 644 | cr 2 1 2 >a wrap wrap 1 ' + perv print \ [| [| [2| 2 3]]] 645 | cr 2 1 2 >a 4 3 2 >a wrap wrap ' + perv print \ [2| [| [2| 4 5]] [| [2| 5 6]]] 646 | \ and so on. 647 | 648 | \ Finally, to simplify calls, we can curry the last argument of "perv": 649 | : perv-+ ['] + perv ; 650 | cr 1 2 perv-+ print \ 3 651 | cr [1] [1] perv-+ print \ [1| 2] 652 | 653 | \ Some other functions we need pervasive: 654 | : perv-and ['] and perv ; 655 | : perv-or ['] or perv ; 656 | : perv-* ['] * perv ; 657 | 658 | \ The test for equality returns 0|1 in APL but 0|-1 in FORTH, so we have to modify it first: 659 | : apl-= = 1 and ; 660 | : perv-= ['] apl-= perv ; 661 | 662 | \ Some more trivial APL array functions: 663 | : hrotate { a u -- a' } a rows u ['] rotate curry map flat a shape-as ; 664 | : vrotate { a u -- a' } a rows u rotate flat a shape-as ; 665 | : reduce ( a xt -- a' ) fold wrap ; 666 | : hreduce { a xt -- a' } a rows xt ['] reduce curry map ; 667 | : vreduce { a xt -- a' } a rows xt fold ; 668 | : vector? rank 1 = ; 669 | : hrotate { a u -- a' } a u a vector? IF rotate ELSE hrotate THEN ; 670 | : hreduce { a xt -- a' } a xt a vector? IF reduce ELSE hreduce THEN ; 671 | 672 | \ The simplified version of the inner product: 673 | : inner-product { * + -- a' } * zip + reduce ; 674 | 675 | \ The generic inner/outer product whose behavior depends on the value of a right-hand function: 676 | : apl-product { al * + ar -- } 677 | + ['] noop = IF al ar * product ELSE al ar * + inner-product THEN ; 678 | 679 | cr _m2x3 ' perv-+ hreduce print \ [2 |6 15 ] 680 | cr _m2x3 ' perv-+ vreduce print \ [3 |5 7 9 ] 681 | 2 1 2 >a Constant _v12 682 | 4 3 2 >a Constant _v34 683 | cr _v12 ' perv-+ reduce print \ 3 684 | cr _v12 _v34 ' perv-+ execute print \ [2| 4 6 ] 685 | cr _v12 _v34 2 >a ' perv-+ reduce print \ [| [2| 4 6 ] ] 686 | 687 | \ At this point we are very close to the Game of Life itself, let's prepare the grid and nice output: 688 | 0 0 0 0 0 0 689 | 0 0 1 0 0 0 690 | 0 0 0 1 0 0 691 | 0 1 1 1 0 0 692 | 0 0 0 0 0 0 693 | 0 0 0 0 0 0 36 >a Constant grid 694 | 6 6 2 >a grid ! 695 | \ This configuration is called a "glider". 696 | 697 | : show { a -- } 698 | a array? 0= IF a . EXIT THEN 699 | a scalar? IF a unwrap recurse EXIT THEN 700 | a vector? IF a FOR i @ recurse EACH EXIT THEN 701 | 'recurse ['] cr compose a rows iter ; 702 | 703 | 704 | 705 | \ 5. APL to FORTH translator 706 | 707 | \ Our final part is a translator for the APL syntax. We want to convert an input string 708 | \ "↑ 1 ⍵ ∨ . ∧ 3 4 = + / , -1 0 1 ∘ . ⊖ -1 0 1 ∘ . ⌽ ⊂ ⍵" 709 | \ into a FORTH code equivalent to following: 710 | grid 711 | wrap 712 | -1 0 1 3 >a ' hrotate product 713 | -1 0 1 3 >a ' vrotate product 714 | ravel 715 | ' perv-+ reduce 716 | 3 4 2 >a perv-= 717 | 1 grid 2 >a ' perv-and ' perv-or inner-product 718 | first 719 | \ This code performs a single step of Game of Life, and 720 | show 721 | \ shows a second stage of a glider evolution. 722 | 723 | \ There is little job to be done during the translation phase. We have to change the execution order 724 | \ from APL (right-to-left with infix functions and operators) into FORTH (left-to-right with postfix 725 | \ functions). Also, we need to append array size to every array literal. -1 0 1 in APL is represented 726 | \ as 1 0 -1 3 in our program. 727 | 728 | \ The translator work is two-phase. First, it tokenizes the input string: words are consumed from left 729 | \ to right and every word put a token on the stack. Second, it compiles the token sequence starting 730 | \ from the top, emitting a FORTH code for every token. For infix functions/operators, the translator 731 | \ will look ahead for one or two lexemes. 732 | 733 | \ We will represent most tokens with a pair {token value, token class}. The token value is a function 734 | \ implementing the operation and token class is a function that compiles the operation into a FORTH 735 | \ code. E.g., 736 | : ⍵ ['] @local0 ['] compile, ; 737 | \ So the omega (stays for a right operand in APL) is a token, its value is "@local0" (the FORTH word 738 | \ to access an argument of a word with single local), and its class is "compile,". Being executed, 739 | \ the class will compile token value into the current definition: 740 | 741 | : _test_dup { _ } [ ⍵ execute ⍵ execute ] ; 742 | cr see _test_dup \ : _test_dup >l @local0 @local0 lp+ ; 743 | cr 3 _test_dup . . \ 3 3 744 | 745 | \ The token representing number is the number itself, see "number?" above. 746 | 747 | \ Below is the core translator function. 748 | \ If a token is a number, compile it into a current word as a literal. 749 | \ Otherwise, execute the token class and let it do what it wants. 750 | : continue ( token -- ) dup number? IF literal, ELSE execute THEN ; 751 | \ Apart from numbers, we'll define the following token classes: 752 | \ function 753 | \ dyadic-op 754 | \ monadic-op 755 | \ open ), an opening parenthesis, start of a sub-expression 756 | \ close (, a closing parenthesis, end of a sub-expression 757 | \ compile, special symbols directly mapped to FORTH, such as identifier ⍵ 758 | 759 | \ Let's implement the abovementioned "-1 0 1" -> "1 0 -1 3" conversion. 760 | 761 | \ The definition of syntax is often recursive, so define a placeholder for mutually-recursive functions 762 | \ below: 763 | defer open 764 | 765 | \ What considered to be a "value" is a number, or a subexpression, or an identifier: 766 | : subexpression? ['] open = ; 767 | : identifier? ['] compile, = ; 768 | : value? { t -- f } t number? t subexpression? or t identifier? or ; 769 | 770 | \ A strand is a sequence of values: 771 | : strand ( .. -- u ) 0 BEGIN { t cnt } t value? WHILE t continue cnt 1+ REPEAT t cnt ; 772 | \ Here we iterate over values, incrementing a counter in progress. Examine it: 773 | 774 | Create mark 775 | : _t [ mark 5 4 3 2 1 strand ] literal [ drop ] ; 776 | cr see _t \ : _t 1 2 3 4 5 5 ; 777 | \ Here, "5 4 3 2 1 strand" compiled into "1 2 3 4 5 5" (what is sufficient for our array creation). 778 | \ The "[ drop ]" in the end is required because the value of "mark" was left on the stack and we need 779 | \ to throw it away before the end of the definition. 780 | 781 | \ To complete the array creation, we have to add the call to array constructor, ">a": 782 | : value strand { size } size 1 > IF size ['] >a compile-curried, THEN ; 783 | 784 | \ Check it works: 785 | : _t [ mark 5 4 3 2 1 value drop ] ; 786 | cr see _t \ : _t 1 2 3 4 5 5 >a ; 787 | : _t [ mark 1 value drop ] ; 788 | cr see _t \ : _t 1 ; 789 | : _t [ mark value drop ] ; 790 | cr see _t \ : _t ; 791 | \ The multiple-element array had been wrapped as an array creation. The single number interpreted 792 | \ as a scalar. An empty strand emits nothing. 793 | 794 | \ Below is the rest of the supported token classes. Note we have to differ between function references 795 | \ (tokens left and right from operator symbol) and function applications (all other cases). For 796 | \ function references, we simply compile the reference into the current word: 797 | : function-ref { t -- } literal, ; 798 | 799 | \ For an operator, we read the next function-ref (one to the left from an operator), then a value 800 | \ (which may be empty in case of monadic operator), then we "compile," an operator (the "xt"), then 801 | \ we continue: 802 | : operator { xt -- } function-ref value xt compile, continue ; 803 | : dyadic-op operator ; 804 | : monadic-op operator ; 805 | 806 | \ For a function, we check if there is a dyadic operator to the left, and then either compile the 807 | \ reference ("literal,"), or read the next value and then compile an application ("compile,"), and 808 | \ then continue: 809 | : function { t xt -- } 810 | t ['] dyadic-op = IF t xt literal, ELSE t value xt compile, THEN continue ; 811 | \ Note: here we assume all functions are either unary or binary (APL monadic or dyadic) which is 812 | \ not true in APL. Information about the arity of any given call is lost precisely here. 813 | 814 | \ An opening parenthesis (an expression) is a value and then optional anything: 815 | :noname value continue ; is open 816 | 817 | \ A closing parenthesis is a no-op. 818 | : close ; 819 | 820 | \ Now the fragment can be tested as a whole; in the following example, we put on the stack the list 821 | \ of tokens: "close", "1", "function +", "2", "open", and then call "continue" to initiate 822 | \ the compilation: 823 | : _t [ ' close 1 ' + ' function 2 ' open continue ] ; 824 | cr see _t \ _t : 2 1 + ; 825 | 826 | \ As effect of "open" is to "continue", we need no explicit call the latter: 827 | : _t [ ' close 1 2 3 4 open ] ; 828 | cr see _t \ _t : 4 3 2 1 4 >a ; 829 | 830 | \ We're almost there, now let's define APL symbols for tokens. We have already defined ⍵, others are 831 | \ very similar, e.g. there is a ⊂ which is a "wrap" function: 832 | : ⊂ ['] wrap ['] function ; 833 | \ To avoid repetitions, we create a new word to define such tokens: 834 | 835 | : apl: { xt -- } : xt literal, ['] function literal, POSTPONE ; ; 836 | \ We can use it as follows: 837 | ' size apl: ≢ 838 | : _t [ ' close ≢ 1 2 3 4 open ] ; 839 | cr see _t \ _t : 4 3 2 1 4 >a size ; 840 | cr _t . \ 4 841 | \ (Really, APL ≢ is not "size"). 842 | 843 | \ We don't want our APL symbols to hide useful FORTH words, so let them live in its own namespace: 844 | wordlist Constant apl 845 | \ The phrase above just creates a new namespace but does not "opens" it. In FORTH there are separated 846 | \ concept of "current" wordlist (the namespace to where newly created words go) and "search order" 847 | \ (the namespace sequence to perform word search). The current wordlist accessed/changed with 848 | \ "get-current" and "set-current", the search order with ">order" and "previous". 849 | 850 | \ So first we'll save the default current wordlist: 851 | get-current 852 | 853 | \ And then set the current wordlist to be "apl": 854 | apl set-current 855 | 856 | \ And now define APL symbols. 857 | \ Symbols for functions are: 858 | ' first apl: ↑ ' perv-or apl: ∨ ' perv-and apl: ∧ 859 | ' perv-= apl: = ' perv-+ apl: + ' ravel apl: , 860 | ' noop apl: ∘ ' vrotate apl: ⊖ ' hrotate apl: ⌽ 861 | ' wrap apl: ⊂ ' perv-* apl: × ' size apl: ≢ 862 | 863 | \ Symbols for operators: 864 | : / ['] hreduce ['] monadic-op ; 865 | : . ['] apl-product ['] dyadic-op ; 866 | 867 | \ And the parenthesis, most simple: 868 | ' close Constant ( 869 | ' open Constant ) 870 | 871 | \ And switch back to the default wordlist: 872 | set-current 873 | 874 | \ Now, in the beginning of an APL section, we will add the apl wordlist to the search order, and in 875 | \ the end of section will drop it with "previous": 876 | : _t [ apl >order ( -1 0 1 ∘ . ⌽ ⊂ 0 1 0 ) continue previous ] ; 877 | cr _t print \ [3 1 |[3 |0 0 1 ] [3 |0 1 0 ] [3 |1 0 0 ] ] 878 | 879 | \ In the code above, starting from "apl >order" the words "(", ")" and "." (and others) have APL 880 | \ meaning, and after "previous" the FORTH meaning restored. Both APL and FORTH parts of the function 881 | \ compiled into FORTH code; FORTH part by FORTH rules, APL part by APL rules. 882 | 883 | \ As all our APL-syntax function will have the same prefix and postfix, make it a words: 884 | : ←{ apl >order ['] close POSTPONE [ ; immediate 885 | : } open previous ] ; immediate 886 | 887 | : _t ←{ -1 0 1 ∘ . ⌽ ⊂ 0 1 0 } ; 888 | 889 | cr _t print \ [3 1 |[3 |0 0 1 ] [3 |0 1 0 ] [3 |1 0 0 ] ] 890 | \ Take a moment to decompile the function and look at its FORTH code: 891 | cr see _t 892 | \ (two big integers here are pointers to "rotate" and "noop"). 893 | 894 | \ So, naturally we've translated APL into FORTH. 895 | 896 | 897 | 898 | 899 | \ Playground 900 | 901 | \ Please note an APL wordlist is just an ordinary FORTH wordlist, so we can extend it incrementally 902 | \ as we define new functions. 903 | 904 | \ Just to be sure every APL word will go to the apl wordlist, let's add a wordlist switching into 905 | \ the definition of "apl:" 906 | : apl: ( xt "name" -- ) { xt } get-current apl set-current xt apl: set-current ; 907 | 908 | \ Let's do some experiments, probably memory-consuming, so mark a memory area to be thrown away later: 909 | marker gc 910 | 911 | \ Some examples from tryapl.org. 912 | \ The pervasive behavior of addition: 913 | : _t ←{ 4 2 3 + 8 5 7 } ; 914 | cr _t print \ [3 |12 7 10 ] 915 | 916 | \ To implement "fac", we first need to implement "iota". We have "integers" which creates integers 917 | \ from 0 to n-1 but iota must create integers from 1 to n: 918 | : iota integers 1 ['] + curry map ; 919 | cr 4 iota .a \ 1 2 3 4 920 | 921 | \ Alternatively, we could implement "iota" in APL: 922 | ' integers apl: integers 923 | : iota ←{ 1 + integers } ; 924 | ' iota apl: ⍳ 925 | 926 | : fac { _ } ←{ × / ⍳ ⍵ } ; 927 | cr 5 fac print \ 120 928 | \ The ugly thing above is "{ _ }". This is required to make function argument accessible thru locals. 929 | \ Of course this can be automated but a chase for perfection would never ends. 930 | 931 | \ To implement "avg", we need a division with correct argument order: 932 | :noname swap / ; 933 | \ Make it pervasive: 934 | ' perv curry 935 | \ Make it available in APL: 936 | apl: ÷ 937 | 938 | : avg { _ } ←{ ( + / ⍵ ) ÷ ≢ ⍵ } ; 939 | cr 40 30 20 10 4 >a avg print \ 25 940 | 941 | \ To implement the frequency counter, we need a pseudorandom number generator: 942 | variable (rnd) 943 | utime drop (rnd) ! 944 | : rnd (rnd) @ dup 13 lshift xor dup 17 rshift xor dup dup 5 lshift xor (rnd) ! ; 945 | cr rnd . rnd . rnd . \ (3 pseudorandom numbers) 946 | 947 | \ A word to return a pseudorandom in range: 948 | :noname ( n -- n ) rnd swap mod 1+ ; 949 | \ Make it pervasive: 950 | ' uperv curry 951 | \ Make it available in APL: 952 | apl: ? 953 | 954 | \ APL rho stays for shape, but in this specific example the constructor "fill" will do: 955 | ' fill apl: ⍴ 956 | 957 | : dices ←{ + / ( ⍳ 6 ) ∘ . = ? 1000 ⍴ 6 } ; 958 | cr dices print \ [6| (6 numbers, totals to 1000)] 959 | gc 960 | 961 | 962 | 963 | 964 | \ The Game of Life 965 | 966 | : life { _ } ←{ ↑ 1 ⍵ ∨ . ∧ 3 4 = + / , -1 0 1 ∘ . ⊖ -1 0 1 ∘ . ⌽ ⊂ ⍵ } ; 967 | 968 | cr ." Memory used by code: " unused0 unused - cell / . ." words" 969 | 970 | marker gc 971 | cr ." The glider:" grid show 972 | cr ." The glider after 4 steps:" grid life life life life show 973 | cr ." Free space on dictionary after a run: " unused . 974 | gc 975 | cr ." Free space on dictionary after gc: " unused . 976 | 977 | bye 978 | 979 | \ apl-life-anno.fs, Conway's Game of Life in APL in FORTH 980 | \ Copyright (c) 2020 Alexander Serkov 981 | 982 | \ This program is free software; you can redistribute it and/or modify it under the terms of 983 | \ the GNU General Public License version 2 as published by the Free Software Foundation. 984 | \ This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 985 | \ without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 986 | \ See the GNU General Public License for more details. 987 | 988 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Conway's Game of Life in APL in FORTH 2 | 3 | I love FORTH and hope to present reasons with this code. 4 | 5 | The original idea was to implement Conway's Game of Life as a one-liner in APL executed in FORTH. (APL is another weird-looking programming language). The goal is mostly reached, with few exceptions. Unary negation symbol ¯ not implemented. APL tokens must be whitespace-separated, as in FORTH. 6 | 7 | FORTH is a low-level language and has no type checking, structures, arrays, let alone higher-level constructs. Instead, it provides a direct access to its interpreter and compiler. This comes to be an extremely powerful tool. It allows us to quickly jump from raw bytes into a world of a problem domain. The code below contains an implementation of 8 | * arrays 9 | * currying and closures 10 | * higher-order functions for collections 11 | * APL specific function application rules, such as pervasion 12 | * APL to FORTH translator (up to extend required to execute Conway's Game of Life) 13 | 14 | All of that is done in ~200 LOC and tooks < 2.5K words of memory. 15 | 16 | For these who had never met FORTH before, "word" in FORTH stays for function and "cell" for machine word. FORTH has no syntax restrictions: code is nothing but a stream of whitespace-separated words. FORTH is interactive: the code below is not only a complete program but also a history of a development session. 17 | 18 | A coding style is affected by an intention to avoid stack manipulation words. Locals are mostly used instead. Hope this might improve readability for people unfamiliar with FORTH. 19 | 20 | This code is written with gforth 0.7.2 and contains Unicode symbols. 21 | 22 | Files 23 | * `README.md` this file, contains the code and explanations 24 | * `apl-life-annotated.fs` the annotated source code, the same contents as this README 25 | * `apl-life.fs` the source code without tests and examples 26 | * `LICENSE.txt` the license 27 | 28 | Output of `apl-life.fs` on my machine is: 29 | ``` 30 | Available free space on the dictionary: 8031610 31 | Machine word size: 8 32 | Memory used by code: 2216 words 33 | The glider: 34 | 0 0 0 0 0 0 35 | 0 0 0 0 0 0 36 | 0 0 1 1 1 0 37 | 0 0 1 0 0 0 38 | 0 0 0 1 0 0 39 | 0 0 0 0 0 0 40 | The glider after 4 steps: 41 | 0 0 0 0 0 0 42 | 0 1 1 1 0 0 43 | 0 1 0 0 0 0 44 | 0 0 1 0 0 0 45 | 0 0 0 0 0 0 46 | 0 0 0 0 0 0 47 | Free space on dictionary after a run: 7226226 48 | Free space on dictionary after gc: 8013882 49 | ``` 50 | 51 | References 52 | * Conway's Game of Life https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life 53 | * Conway's Game of Life in APL in Ruby https://zverok.github.io/blog/2020-05-16-ruby-as-apl.html 54 | * APL programming language https://en.wikipedia.org/wiki/APL_(programming_language) 55 | * John Scholes' Conway's Game of Life in APL https://aplwiki.com/wiki/John_Scholes%27_Conway%27s_Game_of_Life 56 | * online APL playground https://tryapl.org/ 57 | * FORTH programming language https://en.wikipedia.org/wiki/Forth_(programming_language) 58 | * gforth docs https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/ 59 | 60 | ## Arrays 61 | 62 | First we have to implement arrays. APL arrays are multi-dimensional and support nesting which is an unrelated concept (a scalar is a 0-dimensional array, a vector is 1-dimensional, and matrix is 2-dimensional, and a vector of vectors is not a matrix). 63 | 64 | The main idea of the implementation provided below is the fact that array's shape is itself an array, so any array can be represented as a reference to another array and a reference to raw data. The FORTH word for dereferencing is `@` and for incrementing a pointer by one machine word is `cell+`. 65 | 66 | Hereafter non-indented and single-idented lines contain the main program, while double-idented lines contain examples and tests explaining what's going on, and these can be omitted. We will write code in tiny steps and test every line just next to it. Sometimes we will first try things in interpreter mode and then wrap a code in a word definition. 67 | ``` 68 | : shape @ ; 69 | : data cell+ @ ; 70 | : first data @ ; 71 | ``` 72 | We have no function for array creation right now, but as the whole thing is a matter of convention, we can create the first array manually. Anywhere in a memory, suppose at address PTR, we will put a triplet [PTR; PTR+2; 1], and according to the definition above (the words `shape`, `data` and `first`), this triplet can be understood as a 1-dimensional array with a single element, the 1. A triplet [1; PTR; PTR-1] would also do. 73 | 74 | In the line below, there are `Create`, `here`, and `,` some of a most frequently used FORTH words. There is a memory area called Dictionary hosting FORTH words and other program data. The Dictionary is organized as a stack, so is filled continuously and incrementally. `here` is a pointer to free space on top of the Dictionary. `,` (comma) writes a machine word from the data stack to the Dictionary and increments value of `here`. `Create` introduces a new word (whatever is to the right of it) whose meaning is the value of `here` at the moment of the definition). 75 | 76 | So the line below states the following: 77 | ``` 78 | Create [1] \ let the current value of "here" be called [1]. 79 | here \ put the value of "here" on the stack. 80 | , \ write the value from the stack to "here"; increment "here". 81 | here \ put the value of "here" on the stack (now "here" is [1] + 1 machine word). 82 | cell+ \ increment the value on the stack by 1 machine word. 83 | , \ write the value from the stack to "here"; increment "here". 84 | 1 \ put 1 on the stack. 85 | , \ write the value from the stack to "here". 86 | ``` 87 | Thus we have created the [PTR; PTR+2; 1] triplet and assign it a name, `[1]`. 88 | ``` 89 | Create [1] here , here cell+ , 1 , 90 | ``` 91 | We can immediately examine this array with our accessor words: 92 | ``` 93 | cr [1] . \ PTR (some integer value of a pointer) 94 | cr [1] shape . \ PTR (shape of [1] is [1]) 95 | cr [1] data . \ PTR+2 96 | cr [1] first . \ 1 97 | ``` 98 | Note the `[1]` is the only array whose shape is equal to the array itself, so it's naturally the only choice for an array to be created first. 99 | 100 | The very important property of an array is its size. It is not very clear what is size in a general case but what we need first is a size of memory chunk to allocate for array items. A scalar requires 1 memory cell, a vector as many cells as there are items, and a matrix a product of rows and columns. Right now we have no functions to iterate over shape, so let's define `size` for the simplest case of 1-dimensional arrays, like this: 101 | ``` 102 | : size shape first ; 103 | ``` 104 | FORTH allows us to redefine any word, and a new behavior hides an old one. But a words already compiled still refer to the old implementation. In case we want not to hide but retroactively change the meaning of a word, we have to declare it as `deferred`, i.e. linked dynamically. 105 | 106 | The definition of deferred `size` looks like this: 107 | ``` 108 | defer size 109 | :noname shape first ; 110 | is size 111 | ``` 112 | Here is a word to create new arrays at run-time: 113 | ``` 114 | : array { data shape -- a } here shape , data , ; 115 | ``` 116 | Without locals, this could be written as: 117 | ``` 118 | : array ( data shape -- a ) here -rot , , ; 119 | ``` 120 | Which is significantly shorter but not so explanatory. 121 | 122 | We can try it with following line: 123 | ``` 124 | here 0 , [1] array Constant [0] 125 | ``` 126 | Here we have first allocated a single cell of memory and saved 0 here (with a phrase `here 0 ,`, which is readable as well as plain English); then we've provided the array shape, `[1]`; then called the constructor `array` and assigned a name `[0]`. It is a one-dimensional array containing a single value, 0. 127 | ``` 128 | cr [0] . \ some pointer 129 | cr [0] shape . \ PTR (the pointer to [1]) 130 | cr [0] first . \ 0 131 | cr [0] size . \ 1 132 | ``` 133 | An empty array is even simplier, as it does not need allocated data so we can use 0 in place of data pointer: 134 | ``` 135 | 0 [0] array Constant [] 136 | cr [] . \ pointer to [] 137 | cr [] shape . \ pointer to [0] 138 | cr [] size . \ 0 139 | ``` 140 | But it is more convenient to reuse the data pointer of `[1]`, so our (still incomplete) definition of `size` will work properly: 141 | ``` 142 | here 1 , [0] array Constant [] 143 | ``` 144 | ``` 145 | cr [] first . \ 1 146 | ``` 147 | Let's define some more convenient constructors. 148 | Scalar is a zero-dimensional array (i.e., its shape is an empty vector): 149 | ``` 150 | : scalar { u -- a } here u , [] array ; 151 | ``` 152 | The following line creates a scalar with value "101": 153 | ``` 154 | 101 scalar Constant tmp 155 | cr tmp shape . \ pointer to [] 156 | cr tmp first . \ 101 157 | cr tmp size . \ 1 158 | ``` 159 | Vector is a one-dimensional array. Its shape is a single-element vector. A vector constructor accepts a pointer to a pre-allocated data area and a size. It creates a shape vector (`here u , [1] array`) and then calls `array`: 160 | ``` 161 | : vector { data u -- a } data here u , [1] array array ; 162 | ``` 163 | To see it working, we have to manually allocate data here and store some values: 164 | ``` 165 | here 103 , 107 , 166 | ``` 167 | And then we call a vector constructor (the value of `here` is already on the stack): 168 | ``` 169 | 2 vector Constant tmp 170 | cr tmp size . \ 2 171 | cr tmp first . \ 103 172 | cr tmp data cell+ @ . \ 107 173 | ``` 174 | Here is an utility word that allocates a data area for a given number of elements: 175 | ``` 176 | : new { u -- data u } here u cells allot u ; 177 | ``` 178 | Examine it like this: 179 | ``` 180 | 5 new vector Constant tmp 181 | cr tmp size . \ 5 182 | cr tmp first . \ (some value from an unassigned memory cell) 183 | ``` 184 | The vector we've just created is ready but not populated, we can assign values with common memory accessing words: 185 | ``` 186 | 109 tmp data ! 187 | cr tmp first . \ 109 188 | ``` 189 | Now we can define how to iterate over items, that is, to implement the "for each" loop. 190 | 191 | There is several loop words in FORTH, such as `DO`, `?DO`, `LOOP`, `+LOOP`, and `I`, which can be used like this: 192 | ``` 193 | cr 5 0 [DO] [i] . [LOOP] \ 0 1 2 3 4 194 | cr 5 0 [?DO] [i] . 2 [+LOOP] \ 0 2 4 195 | ``` 196 | To iterate over our array items, we need to loop from data start to data end in one-machine-word steps. Here is a word to get a data end: 197 | ``` 198 | : end { a -- addr } a data a size cells + ; 199 | ``` 200 | And here is a word to put on the stack both data end and data start, in this order: 201 | ``` 202 | : (for) { a -- and data } a end a data ; 203 | ``` 204 | Test it by creating two-element vector and definiting a printing function: 205 | ``` 206 | here 113 , 127 , 2 vector Constant tmp 207 | : fn (for) ?DO i ? cell +LOOP ; 208 | cr tmp fn \ 113 127 209 | ``` 210 | This is not very readable, and is error-prone since we can easily forget the word `cell` before `+LOOP`, which would break the pointer arithmetic. But we can easily enhance the language syntax: 211 | ``` 212 | : FOR POSTPONE (for) POSTPONE ?DO ; immediate 213 | : EACH POSTPONE cell POSTPONE +LOOP ; immediate 214 | ``` 215 | And use it like this: 216 | ``` 217 | : .a FOR i ? EACH ; 218 | cr tmp .a \ 113 127 219 | ``` 220 | What's going on here needs a more elaborate explanation. `immediate` words are words executed at compile-time (contrary to words executed at run-time). The word `POSTPONE` says the following word (e.g., `(for)`) will not be normally executed when `FOR` executed but instead will be compiled into the body of a word being defined during execution of `FOR`, which is in our case `.a`. So when compiled the code of `.a` is exactly equivalent to this of `print`. This can be seen with decompiler: 221 | ``` 222 | cr see fn \ : fn (some code follows) 223 | cr see .a \ : .a (the same code) 224 | ``` 225 | You may see this as a sort of macro. With two lines of code, we've extended language syntax with the new construction, "for each" loop working with our arrays. You may want to implement it in your language. 226 | 227 | Here is a word to populate an existing array from the stack: 228 | ``` 229 | : !a ( an .. a1 array -- ) FOR i ! EACH ; 230 | ``` 231 | And a word to create an array and populate it from the stack: 232 | ``` 233 | : >a ( an .. a1 u -- a ) new vector { a } a !a a ; 234 | ``` 235 | ``` 236 | 4 3 2 1 4 >a Constant 1_2_3_4 237 | cr 1_2_3_4 .a \ 1 2 3 4 238 | ``` 239 | Note the reversed element order. 240 | 241 | A word to create an array and fill it with single value: 242 | ``` 243 | : fill { w u -- a } u new vector { a } a FOR w i ! EACH a ; 244 | ``` 245 | ``` 246 | cr 5 4 fill .a \ 5 5 5 5 247 | ``` 248 | Some not-that-pretty-printer supporting recursive/nested arrays: 249 | ``` 250 | : number? abs 32767 <= ; 251 | : array? number? 0= ; 252 | : print { a -- } 253 | a array? IF ." [" a shape .a ." | " a FOR i @ recurse EACH ." ] " ELSE a . THEN ; 254 | ``` 255 | Here I assume our arrays will host only short ints and pointers to other arrays, and its ranges do not overlap. 256 | ``` 257 | cr 131 print \ 131 258 | cr 131 scalar print \ [| 131] 259 | cr 131 1 >a print \ [1| 131] 260 | cr 1_2_3_4 print \ [4| 1 2 3 4] 261 | cr 4 3 2 2 >a 1 3 >a print \ [3| 1 [2| 2 3] 4] 262 | ``` 263 | Following functions perform partitioning/slicing, we will need it later. Note the data is not copied here, but pointers only. 264 | ``` 265 | : before { a n -- a' } a data n vector ; 266 | : after { a n -- a' } a data n cells + a size n - vector ; 267 | : slice { a from count -- a' } a from after count before ; 268 | ``` 269 | ``` 270 | cr 1_2_3_4 2 before .a \ 1 2 271 | cr 1_2_3_4 2 after .a \ 3 4 272 | cr 1_2_3_4 1 2 slice .a \ 2 3 273 | ``` 274 | ## Currying and closures 275 | 276 | There is nothing related to functional programming in FORTH. But as we know the FP is a powerful paradigm we will implement some of its features here. Namely: currying, runtime function composition, and closures. 277 | 278 | Currying is implemented by binding together a function and its last argument. 279 | 280 | Here is how such binding looks like if done at compile time: 281 | ``` 282 | : 10+ 10 + ; 283 | cr see 10+ \ : 10+ 10 + ; 284 | cr 9 10+ . \ 19 285 | ``` 286 | Basically, this is nothing but creating a new short function. The main point is that we want this to happens at run-time, not at compile-time. 287 | 288 | First, our run-time-created function should be unnamed, like this: 289 | ``` 290 | :noname 10 + ; 291 | cr xt-see \ noname: 10 + ; 292 | ``` 293 | Second, the argument value and the function value has to be provided at run-time. Here we will rewrite the previous definition, separating run-time-provided values from the rest of the function body: 294 | ``` 295 | :noname [ 10 ] literal [ ' + compile, ] ; 296 | cr xt-see \ noname: 10 + ; 297 | ``` 298 | The result is equivalent but the source looks differently. The words `[` and `]` switch the FORTH state from compilation to interpretation and back. So the phrase above could be read like: 299 | ``` 300 | :noname \ start the definition of a new unnamed word 301 | [ 10 ] \ at compile-time, put 10 on the stack 302 | literal \ what is on the stack at compile-time gets compiled into 303 | \ the unnamed word we are currently compiling 304 | [ ' + \ at compile-time, put the function + on the stack 305 | compile, \ at compile-time, compile what is on the stack 306 | \ into the unnamed word we are currenly compiling 307 | ] \ ...go back to compilation state 308 | ; \ end of the word 309 | ``` 310 | As you can see with `xt-see`, this word is decompiled extacly as the previous one. 311 | 312 | The word `'` (tick) is one of few so-called parsing words. It takes an input not from the data stack but from the input stream. In the code above, the tick consumes the following `+` from the input stream, so instead of execute `+`, the interpreter put reference to `+` on the stack. 313 | 314 | Values `10` and `' +` could be moved out to some variables: 315 | ``` 316 | 10 Value w 317 | ' + Value xt 318 | :noname [ w ] literal [ xt compile, ] ; 319 | cr xt-see \ noname: 10 + 320 | ``` 321 | And the last step is to make it all to be performed at run-time. Keep in mind the run-time of `curry` is a compile-time of its derived unnamed word. 322 | ``` 323 | : curry { w xt -- xt' } 324 | :noname w POSTPONE literal xt compile, POSTPONE ; 325 | ; 326 | ``` 327 | What was previously done at compile-time (`w`, `xt compile,`) now is done at run-time, so not enclosed in `[ ]`. What must be done at run-time of the derived unnamed word is POSTPONEd. 328 | ``` 329 | w xt curry 330 | cr xt-see \ noname: 10 + 331 | 11 ' - curry 332 | cr xt-see \ noname: 11 - 333 | ``` 334 | It works! 335 | As our definition of `curry` is somewhat long, we will split into 3 words: 336 | ``` 337 | : literal, ( w -- ) POSTPONE literal ; 338 | : compile-curried, { w xt -- } w literal, xt compile, ; 339 | : curry { w xt -- xt' } :noname w xt compile-curried, POSTPONE ; ; 340 | ``` 341 | In the same way we implement a function composition: 342 | ``` 343 | : compose { xt2 xt1 -- xt' } :noname xt1 compile, xt2 compile, POSTPONE ; ; 344 | ``` 345 | Test it by composing the increment `1+` with the output '.'. 346 | ``` 347 | cr ' . ' 1+ compose Constant tmp 348 | cr tmp xt-see \ noname : 1+ . ; 349 | cr 211 tmp execute \ 212 350 | ``` 351 | In case we need to curry not the last but second-from-last argument, we can flip function arguments by composing it with the word `swap`, and then bind the last argument as before: 352 | ``` 353 | : flip ( xt -- xt' ) ['] swap compose ; 354 | ``` 355 | Let's check it with the assymetrical two-argument function "divide": 356 | ``` 357 | \ Divide by 10: 358 | 10 ' / curry Constant /10 359 | cr 30 /10 execute . \ 3 360 | \ Divide 10 by: 361 | 10 ' / flip curry Constant 10/ 362 | cr 5 10/ execute . \ 2 363 | ``` 364 | Closures bind a function to a variable. As we don't use variables, we will use pointers, i.e. bind function directly to a memory cell. A bound function is an unnamed function which first reads a valuefrom the cell, then executes a body of the target function, then writes a value back into the cell. 365 | ``` 366 | : bind-addr { addr xt -- xt' } 367 | :noname 368 | addr ['] @ compile-curried, xt compile, addr ['] ! compile-curried, 369 | POSTPONE ; ; 370 | : bind { w xt -- xt' } here w , xt bind-addr ; 371 | ``` 372 | `bind-addr` binds function to a provided memory cell. 373 | 374 | `bind` allocates a memory cell and writes an initial value here, then bounds. 375 | 376 | In the example below, we create a cell with a value "223" in it, then bind a function `1+` to it. The new function, referenced by `xt`, will increment the value in the cell every time it is called. 377 | ``` 378 | Create tmp 223 , 379 | tmp ' 1+ bind-addr Constant xt 380 | cr tmp ? \ 223 381 | cr xt execute tmp ? \ 224 382 | cr xt execute tmp ? \ 225 383 | ``` 384 | Note: implemented this way, closures require a function to left on top of the stack a value semantically equivalent to a value on top of the stack at function start, i.e. the last argument value. In the example above, binding works as expected because `1+` has the required stack effect `( w -- w )`. It will also work with `+`: 385 | ``` 386 | tmp ' + bind-addr Constant xt 387 | cr 100 xt execute tmp ? \ 325 388 | cr 200 xt execute tmp ? \ 525 389 | ``` 390 | Words which don't follow this pattern must be wrapped accordingly. The `.` word which is `( w -- )` need to be wrapped like this: 391 | ``` 392 | : fn ( w -- w ) dup . ; 393 | tmp ' fn bind-addr Constant xt 394 | cr xt execute \ 525 395 | ``` 396 | -- end of note. 397 | ## Higher-order collection functions 398 | 399 | Now let's implement collection functions such as map. We already have a way to iterate over a collection (the for each loop), but this seems to be not enough, as some functions have to iterate over two or more collections simultaneously. We will implement another well-known solution called an iterator. Actually, the iterator's functionaly overlaps with this of the for each loop, so we would not need the for each if we have full-scale iterators. But we will implement only very basic iterators without any range checkings, and rely on loops for a counting. 400 | 401 | A simple iterator is a pointer that increases its value every time it is read. 402 | 403 | The reading word is `@`, the writing is `!`, and the pointer increment is `cell+`. Here we define words for "read and increment pointer" and "write and increment pointer": 404 | ``` 405 | : !+ { n addr -- addr' } n addr ! addr cell+ ; 406 | : @+ { addr -- n addr' } addr @ addr cell+ ; 407 | ``` 408 | By the way, it can be written much simpler without locals, but stack manipulation words make code look somewhat creepy, or at least cryptic: 409 | ``` 410 | : !+ tuck ! cell+ ; 411 | : @+ dup @ swap cell+ ; 412 | ``` 413 | Try it with the following code. Here we allocate two memory cells with values 101 and 103 and create a pointer `tmp` to the first. After the call to `107 tmp !+` the value 107 is written over the 101, and the incremented value of the pointer is left on the stack. After the next call, `109 swap !+`, the value 109 is written over the 103. 414 | ``` 415 | Create tmp 101 , 103 , 416 | cr tmp ? tmp cell+ ? \ 101 103 417 | cr tmp . \ some ptr 418 | 107 tmp !+ 419 | cr dup . \ ptr to next cell 420 | 109 swap !+ 421 | cr . \ ptr to yet next cell 422 | cr tmp ? tmp cell+ ? \ 107 109 423 | ``` 424 | The iterator is made of `!+` or `@+` bound with a pointer, and the initial pointer value is the data pointer of the target array: 425 | ``` 426 | 1_2_3_4 data ' @+ bind Constant tmp 427 | cr tmp execute . \ 1 428 | cr tmp execute . \ 2 429 | cr tmp execute . \ 3 430 | ``` 431 | As a code snippet works, make it a word: 432 | ``` 433 | : iterator ( a -- xt' ) data ['] @+ bind ; 434 | : inserter ( a -- xt' ) data ['] !+ bind ; 435 | ``` 436 | As we need something with counter to provide range checking, we'll wrap the for each loop into a functional-style iteration: let the word `iter` accept a function and an array and apply the function to every item: 437 | ``` 438 | : iter { xt a -- } a FOR i @ xt execute EACH ; 439 | ``` 440 | ``` 441 | cr ' . 1_2_3_4 iter \ 1 2 3 4 442 | ``` 443 | We could define a "clone" function like this: 444 | ``` 445 | : clone { a -- a' } 446 | a size new vector { a' } 447 | a' inserter 448 | a iter 449 | a' ; 450 | cr 1_2_3_4 clone .a \ 1 2 3 4 451 | ``` 452 | Since many of collection functions we need (map, zip, product...) follow the pattern "create array - create inserter - do something - return newly created array", we will extract the logic into a word: 453 | ``` 454 | : construct { u -- a' xt } u new vector { a' } a' a' inserter ; 455 | ``` 456 | The sequence `{ a' } a' a'` looks especially silly, as it just duplicates a value on the stack, so with your permission I'm going to use one of stack manipulation words, `DUP`: 457 | ``` 458 | : construct ( u -- a' xt) new vector dup inserter ; 459 | ``` 460 | Finally, in the definition of the "clone" above, the resulting array is always a vector, while the function input can have some other shape. 461 | The word to change a shape of an existing array is trivial: 462 | ``` 463 | : shape! ( shape a -- ) ! ; 464 | ``` 465 | But it is more suitable for our needs to left the array on the stack: 466 | ``` 467 | : shape! { a shape -- a } shape a ! a ; 468 | ``` 469 | Or without locals: 470 | ``` 471 | : shape! ( a shape -- a) over ! ; 472 | ``` 473 | The word to copy shape from one array to another can looks like this: 474 | ``` 475 | : shape-as ( a other -- a ) shape shape! ; 476 | ``` 477 | So there are some basic collection functions. 478 | ``` 479 | : map { a xt -- a' } a size construct xt compose a iter a shape-as ; 480 | : zip { al ar xt -- a' } 481 | al size construct xt compose al iterator compose ar iter al shape-as ; 482 | : inject { a xt zero -- w } here { accum } zero , accum xt bind-addr a iter accum @ ; 483 | : fold { a xt -- w } a 1 after xt a first inject ; 484 | : contains { a w -- f } a w ['] = curry map ['] or false inject ; 485 | ``` 486 | Any function could be tested immediately: 487 | ``` 488 | cr 1_2_3_4 ' 1+ map .a \ 2 3 4 5 489 | cr 1_2_3_4 1_2_3_4 ' + zip .a \ 2 4 6 8 490 | cr 1_2_3_4 ' + 10 inject . \ 20 491 | cr 1_2_3_4 ' + fold . \ 10 492 | cr 1_2_3_4 2 contains . \ -1 493 | cr 1_2_3_4 5 contains . \ 0 494 | ``` 495 | Now we can provide the correct implementation for `size`. Note we use `inject` and not `fold` because a shape of a scalar is an empty vector but its size is defined as 1. 496 | ``` 497 | cr 2 3 2 >a ' * 1 inject . \ 6 498 | ``` 499 | Also, we have to protect it from infinite recursion on `[1]`: 500 | ``` 501 | :noname { a -- u } a [1] = IF 1 ELSE a shape ['] * 1 inject THEN ; is size 502 | ``` 503 | Check it: 504 | ``` 505 | cr [1] size . \ 1 506 | cr 1_2_3_4 size . \ 4 507 | 6 5 4 3 2 1 6 >a 3 2 2 >a shape! Constant _m2x3 508 | cr _m2x3 size . \ 6 509 | cr [] size . \ 0 510 | cr 1 [] array size . \ 1 511 | ``` 512 | Note items of nested arrays doesn't count, as expected: 513 | ``` 514 | cr 1_2_3_4 1_2_3_4 2 >a size . \ 2 515 | ``` 516 | Some more collection functions, implemented just for purpose of Game of Life. 517 | 518 | `flat` accepts a homogeneous vector of vectors, and returns a new vector: 519 | ``` 520 | : flat { a -- a' } a ['] size map ['] + fold construct ['] iter flip curry a iter ; 521 | ``` 522 | ``` 523 | cr 1_2_3_4 1_2_3_4 2 >a flat print \ [8| 1 2 3 4 1 2 3 4] 524 | ``` 525 | `product` accepts two vectors and returns a matrix: 526 | ``` 527 | : (product) { w xt al -- } w xt curry al iter ; 528 | : product { al ar xt -- a' } 529 | al size ar size * construct 530 | xt compose al ['] (product) curry curry ar iter 531 | al size ar size 2 >a shape! ; 532 | ``` 533 | ``` 534 | cr 1_2_3_4 20 10 2 >a ' + product print \ [2 4| 11 12 13 14 21 22 23 24] 535 | cr 20 10 2 >a 1_2_3_4 ' + product print \ [4 2| 11 21 12 22 13 23 14 24] 536 | ``` 537 | `rotate` rotates element of a vector: 538 | ``` 539 | : rotate { a offset -- a' } offset a size mod { n } a n before a n after 2 >a flat ; 540 | ``` 541 | ``` 542 | cr 1_2_3_4 1 rotate .a \ 2 3 4 1 543 | cr 1_2_3_4 -1 rotate .a \ 4 1 2 3 544 | ``` 545 | `integers` is a constructor that creates a sequence from 0 to u-1: 546 | ``` 547 | : integers { u -- a } u construct { xt } u 0 ?DO i xt execute LOOP ; 548 | ``` 549 | ``` 550 | cr 4 integers .a \ 0 1 2 3 551 | ``` 552 | `rows` accepts a matrix and returns a vector of vectors: 553 | ``` 554 | : second data cell+ @ ; 555 | : height shape first ; 556 | : width shape second ; 557 | : rows { a -- a' } 558 | a height integers a width ['] * curry map 559 | a a width ['] slice curry flip curry map ; 560 | ``` 561 | ``` 562 | cr _m2x3 print \ [2 3| 1 2 3 4 5 6] 563 | cr _m2x3 rows print \ [2| [3| 1 2 3 ] [3| 4 5 6]] 564 | ``` 565 | ## APL specific functions 566 | 567 | Here we get closer to the APL world. In APL, the array is a basic object. Any numeric value is a scalar an therefore an array (of rank 0). Every item of every array, unless it is a scalar containing a numeric value, is also an array. This is not true in our model. Our arrays can contain not only arrays (including scalars) but also naked numeric values, like this: 568 | ``` 569 | cr 1_2_3_4 print \ [4| 1 2 3 4] 570 | ``` 571 | While the array-only model would represent the same value as follows: 572 | ``` 573 | cr 1_2_3_4 ' scalar map print \ [4| [| 1] [| 2] [| 3] [| 4]] 574 | ``` 575 | Here we update some array functions to work properly with plain numbers. 576 | ``` 577 | : size { a -- u } a array? IF a size ELSE 1 THEN ; 578 | : shape { a -- a' } a array? IF a shape ELSE [] THEN ; 579 | ``` 580 | According to APL rules, we can wrap any array into a scalar, but a number wrapped in a scalar is equal to the number itself. 581 | ``` 582 | : wrap { a -- a' } a array? IF a scalar ELSE a THEN ; 583 | : unwrap { a -- a' } a array? IF a first ELSE a THEN ; 584 | ``` 585 | Here are definitions for basic array properties `rank` and `depth`: 586 | ``` 587 | : rank shape shape first ; 588 | : 'recurse latestxt literal, ; immediate 589 | : depth { a -- a' } a array? IF a 'recurse map ['] max 0 inject 1+ ELSE 0 THEN ; 590 | : scalar? rank 0= ; 591 | ``` 592 | ``` 593 | cr 1 wrap print \ 1 594 | cr [1] wrap print \ [| [1| 1]] 595 | cr 1 unwrap print \ 1 596 | cr 1 scalar unwrap print \ 1 597 | cr 1 rank . \ 0 598 | cr [1] scalar rank . \ 0 599 | cr [1] rank . \ 1 600 | cr _m2x3 rank . \ 2 601 | 602 | cr 1 depth . \ 0 603 | cr [1] depth . \ 1 604 | cr _m2x3 depth . \ 1 605 | cr [1] scalar depth . \ 2 606 | cr [1] scalar scalar depth . \ 3 607 | ``` 608 | Conversion from an arbitrary-shaped array into a 1-dimensional vector: 609 | ``` 610 | : ravel { a -- a' } a data a size vector ; 611 | ``` 612 | One of APL features important for our task is the pervasive function application. If there is a function defined on scalars, such as +, it can be applied to arrays, and its behavior is to traverse thru array elements and apply to each. 613 | 614 | First, we implement the pervasive application of unary function: 615 | ``` 616 | : uperv ( a xt -- a' ) over number? IF execute ELSE 'recurse curry map THEN ; 617 | ``` 618 | ``` 619 | cr 1 ' 1+ uperv print \ 2 620 | cr [1] ' 1+ uperv print \ [1| 2] 621 | cr 1_2_3_4 ' 1+ uperv print \ [4| 2 3 4 5] 622 | 4 3 2 2 >a 1 3 >a Constant tmp 623 | cr tmp ' 1+ uperv print \ [3| 2 [2| 3 4] 5] 624 | ``` 625 | The binary pervasive application is a bit more complicated. It both arguments are arrays, the function is applied to corresponding pairs (as zip). If one argument is an array and another is a scalar, the scalar is "extended" as if it is an array of a required size. In the our case we don't have to create a new array representing this "extended" scalar but will curry the function with the scalar and then map" over the array. 626 | 627 | The implementation going to take more than one word and contain a mutual recursion, so `defer`: 628 | ``` 629 | defer perv 630 | ``` 631 | If both arguments are numbers, 632 | ``` 633 | : both-numbers? { al ar -- f } al number? ar number? and ; 634 | ``` 635 | then simply `execute`, and this is our first runnable version of `perv`: 636 | ``` 637 | :noname { al ar xt -- a' } 638 | al ar both-numbers? IF al ar xt execute EXIT THEN 639 | s" not implemented yet" exception throw ; 640 | is perv 641 | ``` 642 | ``` 643 | cr 1 2 ' + perv print \ 3 644 | ``` 645 | If both arguments can be iterated over, 646 | ``` 647 | : both-iterable? { al ar -- f } al array? ar array? and al rank ar rank = and ; 648 | ``` 649 | then zip: 650 | ``` 651 | : pairwise ( al ar xt -- a' ) ['] perv curry zip ; 652 | ``` 653 | Update the definition of `perv` to test it: 654 | ``` 655 | :noname { al ar xt -- a' } 656 | al ar both-numbers? IF al ar xt execute EXIT THEN 657 | al ar both-iterable? IF al ar xt pairwise EXIT THEN 658 | s" not implemented yet" exception throw ; 659 | is perv 660 | ``` 661 | ``` 662 | cr 1_2_3_4 1_2_3_4 ' + perv print \ [4| 2 4 6 8] 663 | ``` 664 | If the right argument is a scalar and the left is iterable, 665 | ``` 666 | : left-iterable? { al ar -- f } al array? ar scalar? and ; 667 | ``` 668 | then curry xt with the scalar and then map over the array: 669 | ``` 670 | : extend { al ar xt -- a' } al ar unwrap xt ['] perv curry curry map ; 671 | ``` 672 | Update the "perv": 673 | ``` 674 | :noname { al ar xt -- a' } 675 | al ar both-numbers? IF al ar xt execute EXIT THEN 676 | al ar both-iterable? IF al ar xt pairwise EXIT THEN 677 | al ar left-iterable? IF al ar xt extend EXIT THEN 678 | s" not implemented yet" exception throw ; 679 | is perv 680 | ``` 681 | ``` 682 | cr 1_2_3_4 4 ' + perv print \ [4| 5 6 7 8] 683 | ``` 684 | Finally, if the left argument is a scalar and the right is iterable, just swap the arguments and flip the `xt`, then fall to `extend` as above. 685 | 686 | The complete code follows: 687 | ``` 688 | :noname { al ar xt -- a' } 689 | al ar both-numbers? IF al ar xt execute EXIT THEN 690 | al ar both-iterable? IF al ar xt pairwise EXIT THEN 691 | al ar left-iterable? 0= IF ar al xt flip ELSE al ar xt THEN extend ; 692 | is perv 693 | ``` 694 | Examine its behavior: 695 | ``` 696 | cr 1 2 ' + perv print \ 3 697 | cr 1 1_2_3_4 ' + perv print \ [4| 2 3 4 5] 698 | cr 1 1_2_3_4 wrap ' + perv print \ [| [4| 2 3 4 5]] 699 | cr [1] 1_2_3_4 wrap ' + perv print \ [1| [4| 2 3 4 5]] 700 | cr 2 1 2 >a 1_2_3_4 wrap ' + perv print \ [2| [4| 2 3 4 5] [4| 3 4 5 6]] 701 | cr 1_2_3_4 1_2_3_4 ' + perv print \ [4| 2 4 6 8] 702 | cr 1_2_3_4 1_2_3_4 wrap ' + perv print \ [4| [4| 2 3 4 5] [4| 3 4 5 6] [4| 4 5 6 7] [4| 5 6 7 8]] 703 | cr [1] 2 ' + perv print \ [1| 3] 704 | cr 2 [1] ' + perv print \ [1| 3] 705 | cr [1] [1] ' + perv print \ [1| 2] 706 | cr 2 1 2 >a 1 ' + perv print \ [2| 2 3] 707 | cr 2 1 2 >a 4 3 2 >a ' + perv print \ [2| 4 6] 708 | cr 2 1 2 >a 4 3 2 >a wrap ' + perv print \ [2| [2| 4 5] [2| 5 6]] 709 | cr 2 1 2 >a wrap 4 3 2 >a wrap ' + perv print \ [| [2| 4 6]] 710 | cr 2 1 2 >a wrap 4 3 2 >a wrap wrap ' + perv print \ [| [2| [2| 4 5] [2| 5 6]]] 711 | cr 2 1 2 >a wrap 1 ' + perv print \ [| [2| 2 3]] 712 | cr 2 1 2 >a wrap wrap 1 ' + perv print \ [| [| [2| 2 3]]] 713 | cr 2 1 2 >a 4 3 2 >a wrap wrap ' + perv print \ [2| [| [2| 4 5]] [| [2| 5 6]]] 714 | ``` 715 | and so on. 716 | 717 | Finally, to simplify calls, we can curry the last argument of `perv`: 718 | ``` 719 | : perv-+ ['] + perv ; 720 | ``` 721 | ``` 722 | cr 1 2 perv-+ print \ 3 723 | cr [1] [1] perv-+ print \ [1| 2] 724 | ``` 725 | Some other functions we need pervasive: 726 | ``` 727 | : perv-and ['] and perv ; 728 | : perv-or ['] or perv ; 729 | : perv-* ['] * perv ; 730 | ``` 731 | The test for equality returns 0|1 in APL but 0|-1 in FORTH, so we have to modify it first: 732 | ``` 733 | : apl-= = 1 and ; 734 | : perv-= ['] apl-= perv ; 735 | ``` 736 | Some more trivial APL array functions: 737 | ``` 738 | : hrotate { a u -- a' } a rows u ['] rotate curry map flat a shape-as ; 739 | : vrotate { a u -- a' } a rows u rotate flat a shape-as ; 740 | : reduce ( a xt -- a' ) fold wrap ; 741 | : hreduce { a xt -- a' } a rows xt ['] reduce curry map ; 742 | : vreduce { a xt -- a' } a rows xt fold ; 743 | : vector? rank 1 = ; 744 | : hrotate { a u -- a' } a u a vector? IF rotate ELSE hrotate THEN ; 745 | : hreduce { a xt -- a' } a xt a vector? IF reduce ELSE hreduce THEN ; 746 | ``` 747 | The simplified version of the inner product: 748 | ``` 749 | : inner-product { * + -- a' } * zip + reduce ; 750 | ``` 751 | The generic inner/outer product whose behavior depends on the value of a right-hand function: 752 | ``` 753 | : apl-product { al * + ar -- } 754 | + ['] noop = IF al ar * product ELSE al ar * + inner-product THEN ; 755 | ``` 756 | ``` 757 | cr _m2x3 ' perv-+ hreduce print \ [2 |6 15 ] 758 | cr _m2x3 ' perv-+ vreduce print \ [3 |5 7 9 ] 759 | 2 1 2 >a Constant _v12 760 | 4 3 2 >a Constant _v34 761 | cr _v12 ' perv-+ reduce print \ 3 762 | cr _v12 _v34 ' perv-+ execute print \ [2| 4 6 ] 763 | cr _v12 _v34 2 >a ' perv-+ reduce print \ [| [2| 4 6 ] ] 764 | ``` 765 | 766 | At this point we are very close to the Game of Life itself, let's prepare the grid and nice output: 767 | ``` 768 | 0 0 0 0 0 0 769 | 0 0 1 0 0 0 770 | 0 0 0 1 0 0 771 | 0 1 1 1 0 0 772 | 0 0 0 0 0 0 773 | 0 0 0 0 0 0 36 >a Constant grid 774 | 6 6 2 >a grid ! 775 | ``` 776 | This configuration is called a "glider". 777 | ``` 778 | : show { a -- } 779 | a array? 0= IF a . EXIT THEN 780 | a scalar? IF a unwrap recurse EXIT THEN 781 | a vector? IF a FOR i @ recurse EACH EXIT THEN 782 | 'recurse ['] cr compose a rows iter ; 783 | ``` 784 | ## APL to FORTH translator 785 | 786 | Our final part is a translator for the APL syntax. We want to convert an input string `↑ 1 ⍵ ∨ . ∧ 3 4 = + / , -1 0 1 ∘ . ⊖ -1 0 1 ∘ . ⌽ ⊂ ⍵` into a FORTH code equivalent to following: 787 | ``` 788 | grid 789 | wrap 790 | -1 0 1 3 >a ' hrotate product 791 | -1 0 1 3 >a ' vrotate product 792 | ravel 793 | ' perv-+ reduce 794 | 3 4 2 >a perv-= 795 | 1 grid 2 >a ' perv-and ' perv-or inner-product 796 | first 797 | ``` 798 | This code performs a single step of Game of Life, and 799 | ``` 800 | show 801 | ``` 802 | shows a second stage of a glider evolution. 803 | 804 | There is little job to be done during the translation phase. We have to change the execution order from APL (right-to-left with infix functions and operators) into FORTH (left-to-right with postfix functions). Also, we need to append array size to every array literal. -1 0 1 in APL is represented as 1 0 -1 3 in our program. 805 | 806 | The translator work is two-phase. First, it tokenizes the input string: words are consumed from left to right and every word put a token on the stack. Second, it compiles the token sequence starting from the top, emitting a FORTH code for every token. For infix functions/operators, the translator will look ahead for one or two lexemes. 807 | 808 | We will represent most tokens with a pair {token value, token class}. The token value is a function implementing the operation and token class is a function that compiles the operation into a FORTH code. E.g., 809 | ``` 810 | : ⍵ ['] @local0 ['] compile, ; 811 | ``` 812 | So the omega (stays for a right operand in APL) is a token, its value is `@local0` (the FORTH word to access an argument of a word with single local), and its class is "compile,". Being executed, the class will compile token value into the current definition: 813 | ``` 814 | : _test_dup { _ } [ ⍵ execute ⍵ execute ] ; 815 | ``` 816 | ``` 817 | cr see _test_dup \ : _test_dup >l @local0 @local0 lp+ ; 818 | cr 3 _test_dup . . \ 3 3 819 | ``` 820 | The token representing number is the number itself, see `number?` above. 821 | 822 | Below is the core translator function. If a token is a number, compile it into a current word as a literal. Otherwise, execute the token class and let it do what it wants. 823 | ``` 824 | : continue ( token -- ) dup number? IF literal, ELSE execute THEN ; 825 | ``` 826 | Apart from numbers, we'll define the following token classes: 827 | * function 828 | * yadic-op 829 | * monadic-op 830 | * open ), an opening parenthesis, start of a sub-expression 831 | * close (, a closing parenthesis, end of a sub-expression 832 | * compile, special symbols directly mapped to FORTH, such as identifier ⍵ 833 | 834 | Let's implement the abovementioned "-1 0 1" -> "1 0 -1 3" conversion. 835 | 836 | The definition of syntax is often recursive, so define a placeholder for mutually-recursive functions below: 837 | ``` 838 | defer open 839 | ``` 840 | 841 | What considered to be a "value" is a number, or a subexpression, or an identifier: 842 | ``` 843 | : subexpression? ['] open = ; 844 | : identifier? ['] compile, = ; 845 | : value? { t -- f } t number? t subexpression? or t identifier? or ; 846 | ``` 847 | A strand is a sequence of values: 848 | ``` 849 | : strand ( .. -- u ) 0 BEGIN { t cnt } t value? WHILE t continue cnt 1+ REPEAT t cnt ; 850 | ``` 851 | Here we iterate over values, incrementing a counter in progress. Examine it: 852 | ``` 853 | Create mark 854 | : _t [ mark 5 4 3 2 1 strand ] literal [ drop ] ; 855 | cr see _t \ : _t 1 2 3 4 5 5 ; 856 | ``` 857 | Here, `5 4 3 2 1 strand` compiled into `1 2 3 4 5 5` (what is sufficient for our array creation). The `[ drop ]` in the end is required because the value of `mark` was left on the stack and we need to throw it away before the end of the definition. 858 | 859 | To complete the array creation, we have to add the call to array constructor, `>a`: 860 | ``` 861 | : value strand { size } size 1 > IF size ['] >a compile-curried, THEN ; 862 | ``` 863 | Check it works: 864 | ``` 865 | : _t [ mark 5 4 3 2 1 value drop ] ; 866 | cr see _t \ : _t 1 2 3 4 5 5 >a ; 867 | : _t [ mark 1 value drop ] ; 868 | cr see _t \ : _t 1 ; 869 | : _t [ mark value drop ] ; 870 | cr see _t \ : _t ; 871 | ``` 872 | The multiple-element array had been wrapped as an array creation. The single number interpreted as a scalar. An empty strand emits nothing. 873 | 874 | Below is the rest of the supported token classes. Note we have to differ between function references (tokens left and right from operator symbol) and function applications (all other cases). For function references, we simply compile the reference into the current word: 875 | ``` 876 | : function-ref { t -- } literal, ; 877 | ``` 878 | For an operator, we read the next function-ref (one to the left from an operator), then a value (which may be empty in case of monadic operator), then we `compile,` an operator (the `xt`), then we continue: 879 | ``` 880 | : operator { xt -- } function-ref value xt compile, continue ; 881 | : dyadic-op operator ; 882 | : monadic-op operator ; 883 | ``` 884 | For a function, we check if there is a dyadic operator to the left, and then either compile the reference (`literal,`), or read the next value and then compile an application (`compile,`), and then continue: 885 | ``` 886 | : function { t xt -- } 887 | t ['] dyadic-op = IF t xt literal, ELSE t value xt compile, THEN continue ; 888 | ``` 889 | Note: here we assume all functions are either unary or binary (APL monadic or dyadic) which is not true in APL. Information about the arity of any given call is lost precisely here. 890 | 891 | An opening parenthesis (an expression) is a value and then optional anything: 892 | ``` 893 | :noname value continue ; is open 894 | ``` 895 | A closing parenthesis is a no-op. 896 | ``` 897 | : close ; 898 | ``` 899 | Now the fragment can be tested as a whole; in the following example, we put on the stack the list of tokens: `close`, `1`, `function +`, `2`, `open`, and then call `continue` to initiate the compilation: 900 | ``` 901 | : _t [ ' close 1 ' + ' function 2 ' open continue ] ; 902 | cr see _t \ _t : 2 1 + ; 903 | ``` 904 | As effect of `open` is to `continue`, we need no explicit call the latter: 905 | ``` 906 | : _t [ ' close 1 2 3 4 open ] ; 907 | cr see _t \ _t : 4 3 2 1 4 >a ; 908 | ``` 909 | We're almost there, now let's define APL symbols for tokens. We have already defined ⍵, others are very similar, e.g. there is a `⊂` which is a `wrap` function: 910 | ``` 911 | : ⊂ ['] wrap ['] function ; 912 | ``` 913 | To avoid repetitions, we create a new word to define such tokens: 914 | ``` 915 | : apl: { xt -- } : xt literal, ['] function literal, POSTPONE ; ; 916 | ``` 917 | We can use it as follows: 918 | ``` 919 | ' size apl: ≢ 920 | : _t [ ' close ≢ 1 2 3 4 open ] ; 921 | cr see _t \ _t : 4 3 2 1 4 >a size ; 922 | cr _t . \ 4 923 | ``` 924 | (Really, APL `≢` is not a `size`). 925 | 926 | We don't want our APL symbols to hide useful FORTH words, so let them live in its own namespace: 927 | ``` 928 | wordlist Constant apl 929 | ``` 930 | The phrase above just creates a new namespace but does not "opens" it. In FORTH there are separated concept of "current wordlist" (the namespace to where newly created words go) and "search order" (the namespace sequence to perform word search). The current wordlist accessed/changed with `get-current` and `set-current`, the search order with `>order` and `previous`. 931 | 932 | So first we'll save the default current wordlist: 933 | ``` 934 | get-current 935 | ``` 936 | And then set the current wordlist to be `apl`: 937 | ``` 938 | apl set-current 939 | ``` 940 | And now define APL symbols. 941 | Symbols for functions are: 942 | ``` 943 | ' first apl: ↑ ' perv-or apl: ∨ ' perv-and apl: ∧ 944 | ' perv-= apl: = ' perv-+ apl: + ' ravel apl: , 945 | ' noop apl: ∘ ' vrotate apl: ⊖ ' hrotate apl: ⌽ 946 | ' wrap apl: ⊂ ' perv-* apl: × ' size apl: ≢ 947 | ``` 948 | Symbols for operators: 949 | ``` 950 | : / ['] hreduce ['] monadic-op ; 951 | : . ['] apl-product ['] dyadic-op ; 952 | ``` 953 | And the parenthesis, most simple: 954 | ``` 955 | ' close Constant ( 956 | ' open Constant ) 957 | ``` 958 | And switch back to the default wordlist: 959 | ``` 960 | set-current 961 | ``` 962 | Now, in the beginning of an APL section, we will add the apl wordlist to the search order, and in the end of section will drop it with `previous`: 963 | ``` 964 | : _t [ apl >order ( -1 0 1 ∘ . ⌽ ⊂ 0 1 0 ) continue previous ] ; 965 | cr _t print \ [3 1 |[3 |0 0 1 ] [3 |0 1 0 ] [3 |1 0 0 ] ] 966 | ``` 967 | In the code above, starting from `apl >order` the words `(`, `)` and `.` (and others) have APL meaning, and after `previous` the FORTH meaning restored. Both APL and FORTH parts of the function compiled into FORTH code; FORTH part by FORTH rules, APL part by APL rules. 968 | 969 | As all our APL-syntax function will have the same prefix and postfix, make it a words: 970 | ``` 971 | : ←{ apl >order ['] close POSTPONE [ ; immediate 972 | : } open previous ] ; immediate 973 | ``` 974 | ``` 975 | : _t ←{ -1 0 1 ∘ . ⌽ ⊂ 0 1 0 } ; 976 | cr _t print \ [3 1 |[3 |0 0 1 ] [3 |0 1 0 ] [3 |1 0 0 ] ] 977 | ``` 978 | Take a moment to decompile the function and look at its FORTH code: 979 | ``` 980 | cr see _t 981 | ``` 982 | (two big integers here are pointers to `rotate` and `noop`). 983 | 984 | So, naturally we've translated APL into FORTH. 985 | ## Playground 986 | 987 | Please note an APL wordlist is just an ordinary FORTH wordlist, so we can extend it incrementally as we define new functions. 988 | 989 | Just to be sure every APL word will go to the apl wordlist, let's add a wordlist switching into the definition of `apl:` 990 | ``` 991 | : apl: ( xt "name" -- ) { xt } get-current apl set-current xt apl: set-current ; 992 | ``` 993 | Let's do some experiments, probably memory-consuming, so mark a memory area to be thrown away later: 994 | ``` 995 | marker gc 996 | ``` 997 | Some examples from tryapl.org. 998 | 999 | The pervasive behavior of addition: 1000 | ``` 1001 | : _t ←{ 4 2 3 + 8 5 7 } ; 1002 | cr _t print \ [3 |12 7 10 ] 1003 | ``` 1004 | To implement `fac`, we first need to implement `iota`. We have `integers` which creates integers from 0 to n-1 but `iota` must create integers from 1 to n: 1005 | ``` 1006 | : iota integers 1 ['] + curry map ; 1007 | cr 4 iota .a \ 1 2 3 4 1008 | ``` 1009 | Alternatively, we could implement `iota` in APL: 1010 | ``` 1011 | ' integers apl: integers 1012 | : iota ←{ 1 + integers } ; 1013 | ' iota apl: ⍳ 1014 | ``` 1015 | ``` 1016 | : fac { _ } ←{ × / ⍳ ⍵ } ; 1017 | cr 5 fac print \ 120 1018 | ``` 1019 | The ugly thing above is `{ _ }`. This is required to make function argument accessible thru locals. Of course this can be automated but a chase for perfection would never ends. 1020 | 1021 | To implement `avg`, we need a division with correct argument order: 1022 | ``` 1023 | :noname swap / ; 1024 | ``` 1025 | Make it pervasive: 1026 | ``` 1027 | ' perv curry 1028 | ``` 1029 | Make it available in APL: 1030 | ``` 1031 | apl: ÷ 1032 | ``` 1033 | ``` 1034 | : avg { _ } ←{ ( + / ⍵ ) ÷ ≢ ⍵ } ; 1035 | cr 40 30 20 10 4 >a avg print \ 25 1036 | ``` 1037 | To implement the frequency counter, we need a pseudorandom number generator: 1038 | ``` 1039 | variable (rnd) 1040 | utime drop (rnd) ! 1041 | : rnd (rnd) @ dup 13 lshift xor dup 17 rshift xor dup dup 5 lshift xor (rnd) ! ; 1042 | cr rnd . rnd . rnd . \ (3 pseudorandom numbers) 1043 | ``` 1044 | A word to return a pseudorandom in range, pervasive, available in APL: 1045 | ``` 1046 | :noname ( n -- n ) rnd swap mod 1+ ; ' uperv curry apl: ? 1047 | ``` 1048 | APL `rho` stays for shape, but in this specific example the constructor `fill` will do: 1049 | ``` 1050 | ' fill apl: ⍴ 1051 | ``` 1052 | ``` 1053 | : dices ←{ + / ( ⍳ 6 ) ∘ . = ? 1000 ⍴ 6 } ; 1054 | cr dices print \ [6| (6 numbers, totals to 1000)] 1055 | ``` 1056 | ``` 1057 | gc 1058 | ``` 1059 | ## The Game of Life 1060 | 1061 | ``` 1062 | : life { _ } ←{ ↑ 1 ⍵ ∨ . ∧ 3 4 = + / , -1 0 1 ∘ . ⊖ -1 0 1 ∘ . ⌽ ⊂ ⍵ } ; 1063 | 1064 | cr ." Memory used by code: " unused0 unused - cell / . ." words" 1065 | 1066 | marker gc 1067 | cr ." The glider:" grid show 1068 | cr ." The glider after 4 steps:" grid life life life life show 1069 | cr ." Free space on dictionary after a run: " unused . 1070 | gc 1071 | cr ." Free space on dictionary after gc: " unused . 1072 | ``` 1073 | --------------------------------------------------------------------------------