uir VOLUME Numbers 1-6 ...... FORT3 DIMENSIONS INDEX INDEX COMPILED COURTESY OF * * VOLUME I, 11, 111 M. TASSANO * * 936 DELAWARE WAY * * LIVERMORE, CA 94550 * ......

ADDING MODULES, STRUCTURED PROGRAMMING 11,132

APPLE-4TH CASE II,62 ART IFI C I AL LING U I S'r I CS 111,138

ASSEMBLER, 6502 111,143

ASSEMBLER, 8080 111,180

BALANCED TREE DELETION IN FASL II,96

BASIC REVISITED 111,175

BEGINNER'S STUMBLING BLOCK II,23

BENCHMARK, PROJECT 11,112

BOOK REVIEW, STARTING FORTH III,76

BRINGING UP 8080 III,40

:CASE II,41

CASE AND PROD CONSTRUCTS II,53

CASE AS A DEFINING WORD 111,189

CASE AUGMENTED 111,187

CASE CONTEST STATEMENT II,73

CASE IMPLEMENTATION II,60

CASE STATEMENT 11,55

CASE STATEMENT II,81

CASE STATEMENT II,82

CASE STATEMENT II,84

CASE STATEMENT II,87

FORTH DIMENSIONS Page 1 INDEX CONTINUED

CASE, SEL, AND COND STRUCTURES 11,116

CASES CONTINUED 111,187

CHARLES MOORE, Speech to a Forth Convention I,60

COMPILER SECURITY III,15 How it works and how it doesn't

COMPLEX ANALYSIS IN FORTH 111,125

CONTROL STRUCTURES, TRANSPORTABLE 111,176 Wi th compiler Security

CORRECTIONS 'TO METAFORTH III,41

CP/M, SKEWED SECTORS FOR 111,182

D-C HARTS I,30

DATA BASE DESIGN, ELEMENTS OF III,45

DATA STRUCTURES 111,110 in a telecommunications front end

DATA STRUCTURES, OPTIMIZED FOR HARDW.CONTROL 111,118

DECOMPILER FOR SYN-FORTH III,61

DEFINING WORDS, NEW SYNTAX FOR DEFINING 11,121

DEVELOPMENT OF A DUMP UTILITY 11,170

DIAGNOSTICS ON DISK BUFFERS 111,183

DICTIONARY SEARCHES II1,57

DISCUSSION OF 'TO' II,19

DISK ACCESS SPEED INCREASE III,53

DISK BUFFERS, DIAGNOSTICS ON 111,183

DISK COPYING, CHANGING 8080 FIG III,42

DO-CASE EXTENSIONS II,64 ! DO-CASE STATEMENT II,57

DTC VS. ITC ON PDP-11 I,25 i DUMP UTILITY, DEVELOPMENT OF 11,170

EDITOR 11,142

EDITOR III,80 FORTH Inc., FIG, Starting FORTH

FORTH DIMENSIONS Page 2 INDEX CONTINUED

ED1TOR EXTENS IONS 11,156

EIGHT QUEENS PROBLEM 11,6

ENTRY FOR FIG CASE CONTEST 11,67

ERATOSTHENES, SIEVE OF III,iai

EVOLUTION OF A FORTH FREAK 1,3

EXECUTION VARIABLE AND ARRAY 11,109

EXECUTION VECTORS 111,174

EXTENSIBILITY WITH FORTH 1,13

FASL, BALANCED TREE DELETION 11,96

FILE EDITOR 11,142

FILE NAMING SYSTEM 11,29

FLOATING POINT ON TRS-80 111,184

FOR NEWCOMERS 1,11

FORGET, "SMART" 11,154

FORGIVING FORGET 11,154

FORTH AND THE UNIVERSITY 111,101

FORTH CASE STATEMENT 11,7a

FORTH DEFINITION 1,18

FORTH DIALECT, GERMAN, IPS 11,113

FORTH ENGINE III,~~

FORTH IMPLEMENTATION PROJECT 1,41

FORTH IN LASER FUSION I 11,102

FORTH IN LITERATURE ! ii,9 FORTH LEARNS GERMAN 1,5

I FORTH LEARNS GERMAN, Part 2 i,15

FORTH POEM ':SONG' 1,63

FORTH VS. ASSEMBLY 1,33

FORTH DIMENSIONS Page 3 INDEX CONTINUED

FORTH, IMPLEMENTING AT UNIV. ROCHESTER 111,105

FORTH, The last ten years & next 2 weeks i,60 Speech by Charles Moore

FORTH-85 "CASE" STATEMENT 1,50

FUNCTIONAL PROGRAMMING AND FORTH 111,137

GAME OF 31 111,154

GAME OF MASTERMIND III,158

GAME OF REVERSE 111,152

GAME, TOWERS OF HANOI 11,32

GENERALIZED CASE STRUCTURE 111,190

GENERALIZED LOOP CONSTRUCT 11,26

GERMAN FORTH DIALECT, IPS 11,113

GERMAN REVISITED 1,15

GERMAN, FORTH LEARNS 1t5

GERMAN, FORTH LEARNS, Part 2 1,15

GLOSSARY DOCUMENTATION 1,44

GOD0 CONSTRUCT, KITT PEAK 11,89

GRAPHIC GRAPHICS 111,185

GRAPHICS, SIMULATED TEK. 4010 111,155

GRAPHICS, TOWERS OF HANOI 11,32

GREATEST COMMON DIVISOR 11,156

HELP 1,19

HIGH SPEED DISK COPY 1,34

IMPLEMENTATION NO'i'LS, 6809 11,3

INCREASING DISK ACCESS SPEED, FIG III,53

INPUT NUMBER WORD SET 11,129

INTERRUPT HANDLER 111,116

IPS, GERMAN FORTH DIALECT 11,113

JUST IN CASE 11,37

FORTH DIMENSIONS Page 4 INDEX CONTINUED

KITT PEAK GOD0 CONSTRUCT

LOCAL VARIABLES, TURNING STACK INTO

LOOP, A GENERALIZED CONSTRUCT

MAPPED MEMORY MANAGEMENT

MARKETING COLUMN

MASTERMIND, GAME OF

METAFORTH, CORRECTIONS TO

MICRO ASSEMBLER, MICRO-SIZE

MODEM, TRANSFER SCREENS BY

MODEST PROPOSAL FOR DICTIONARY HEADERS

MORE FROM GEORGE ( Pascal vs. Forth )

MUSIC GENERATION

NEW SYNTAX FOR DEFINING DEFINING WORDS

NOVA BUGS

OPTIMIZING DICTIONARY SEARCHES

PARAMETER PASSING TO DOES>

PASCAL VS. FORTH ( MORE FROM GEORGE )

PDP-11, DTC VS. ITC

POEM

PROGRAMMING HINTS

PROJECT BENCHMARK

PROPOSED CASE STATEMENT

RECURSION AND ACKERMANN FUNCTION

RECURSION, EIGHT QUEENS PROBLEM

RECURSION, ROUNTABLE ON

REVERSE, GAME OF

ROUNDTABLE ON RECURSION

SEARCH

FORTH DIMENSIONS Page 5 INDEX CONTINUED t USING 'ENCLOSE' ON 8080 USING FORTH FOR TRADEOFFS I Be tween ha rdwa re/ f i rmwa re/so f twa re VARIABLE AND ARRAY, EXECUTION

VIEW OR NOT TO VIEW

W, RENAME

WHAT IS THE FORTH INTEREST GROUP?

WORD SET, INPUT NUMBER

WORDS ABOUT WORDS

l..'.. 11,168 'ASCII ' III,72 Instead of EMIT

:CASE

'CASE', A GENERALIZED STRUCTURE

'CASE', BOCHERT/LION

'CASE', BRECHER

'CASE', BROTHERS

'CASE', EAKER

'CASE', EMERY

'CASE', FITTERY

'CASE', KATTENBERG

'CASE', LYONS

'CASE', MUNSON

'CASE', PERRY

'CASE', POWELL

'CASE', SELZER

'CASE', WILSON

FORTH DIMENSIONS Page 7 WORDS CONTINUED

'CASE', WITT/BUSLER ii,87

'CVD', CONVERT TO DECIMAL 111,142

'DO-CASE', ELVEY ii,57

'DO-CASE' I GILES 11,64

'ENCLOSE', 6502 CORRECTION 111,170

'ENDWHILE' III,72

'GODO', KITT PEAK 11,89

'SEARCH' 11,165

'TO' SOLUTION 1,38

'TO' SOLUTION CONTINUED 1,48

'VIEW' 11,164

'XEQ' 11,109

31, GAME OF 111,154

6502 'TINY' PSUEDO-CODE 11,7

6502, ASSEMBLER 111,143

6502, CORRECTIONS FOR 'ENCLOSE' 111,170 6800, LISTING, TREE DELETION 11,105

6809 IMPLEMENTATON NOTES 11,3

79 STANDARD 111,139

79 STANDARD - A TOOL BOX? III,74 79 STANDARD, 'FILL' II1,42

79 STANDARD, 'WORD' III,73

79 STANDARD, CONTINUING DIAL% 111,5

79 STANDARD, DO, LOOP, +LOOP I XI, 172

8080 ASSEMBLER 111,180

8080, FIG DISK COPYING II1,42

FORTH DIMENSIONS MISC. CONTINUED

8080, TIPS ON BRINGING UP III,40 9900 TRACE 111,173

FORTH DIMENSIONS Page 9 INDEX CONTINUED

ASSEMBLER FOR 6502 111,149

ASSEMBLER FOR 8080 111,180

BASIC COMPILER FOR FIG 111,177

' BATCH-COPY' III,54

'BUILDS, 'DOES' 11,128

CASE AS A DEFINING WORD 111,189

CASE AUGMENTED 111,187

'CASE', BOCHERT/LION 11,52

'CASE', BRECHER 11,54

'CASE', BROTHERS 11,55

CASES CONTINUED 111, 187

'CASE', EAKER 11,38

'CASE', EMERY 11,60

'CASE', FITTERY 11,62

'CASE', FORTH-85 1,50

'CASE' , GENERALIZED STRUCTURE

'CASE', KATTENBERG 11t68

' CASE ' , MUNSON

'CASE', PERRY

CASE, SEL, AND COND

' CASE ' , SELZ ER ' CASE ' , WILSON 11,85

'CASE', WITT/BUSLER 11,87

DATA BASE ELEMENTS III,45

DATA STRUCTURES 111,118

DECOMPILER FOR SYN-FORTH III,61

SCREENS Page 10 SCREENS CONTINUED

DISK BUFFER LIIAGNOSTICS 111,183

'DO-CASE', ELVEY II,57

'D3-CASE' , GILES II,66

EDITOR III,84

EDITOR EXTENSIONS 11,157

EDITOR EXTENSIONS 11, 161

EIGHT QUEENS PROBLEM II,6

EXECUTION VARIABLE 11,111

' EXPECT' II1,7 with user defined backspace

FILE EDITOR 11,142

FILE NAMING SYSTEM II,30

FORGIVING FORGET 11,155

FORTH LEARNS GERMAN If5

GAME OF 31 111,154

GAME OF MASTERMIND 111,158

GAME OF REVERSE 111,152

GLOSSARY DOCUMENTATION I,44

GLOSSARY GENERATOR III,7

GRAPHICS (TEK 4010 SIMULATION) 111,156

GREATEST COMMON DIVISOR 11,167

HELP I,19

HIGH SPEED DISK COPY I,34

HUNT FOR CONTROL CHARS. 111,140

INPUT NUMBER WORDS 11,131

INTERRUPT HANDLER 111,117

JULIAN DATE 111,137

LOOP CONSTRUCT II,26

SCREENS Page 11 SCREENS CONT I NU E D

'MATCH' FOR EDITORS 11,177 MICRO ASSEMBLER 111,128 MODEM 111,162 MUSIC GENERATION III,54

OPTIMIZ ING DIC'I'I ONARY SEARCHES III,57 PROJECT BENCHMARK 11,112 RANDOM NUMBER GENERATOR II,34 ' SEARCH ' II1,lO for a string over a range of screens

SECTOR SKEWING FOR CP/M 111,182 SIEVE OF ERATOSTHEN ES 111,181

SOFTWARE TOOLS III,10 STACK DIAGRAM PACKAGE III,30 STACK INTO VARIABLES 111,185 STRING STACK 111,121 SYMBOL DICTIONARY 11,150 THEORY THAT JACK BUILT II,9 'TO' SOLUTION I,40 'TO' SOLUTION CONTINUED I,48 TOWERS OF HANOI II,32 TRACE COLON WORDS III,58 TRANSIENT DEFINITIONS I11, 171 TREE DELETION IN FASL 11,103 TRS-80 FLOATING POINT 111,184 'VIEW' III,11 using 'where'

I..'.. 11,168 6502 ASSEMBLER 111,149 8080 ASSEMBLER 111,180

SCREENS Page 12 ~ ~~~ ~~~~~~ ~~ ~-

FORTH INTEREST GROUP Volume II P.O. Box 1105 Number 1 San Carlos, CA 94070 Price $2.00

1 General Information

Publisher's Column

3 FORTH for the Motorola 6809

6 Recursion - The Eight Queens Problem

7 A 'TINY' Pseudo-Code

9 FORTH in Literature

10 News & FIG Doings

12 New Products

15 Letters Published by Fath Interest Qoup June 8-13 -icm Ckmical Society

Mime I1 ND. 1 Itay/June 1980 Junc 21 So. Cal. FIG Meeting, MSI Data Corp., 300 Fi&r Ave., Costa ksa, C4. "I. FUbliSher by C. Martens June 28 FIG Monthly Meeting, 1:OO pm, at Liberty Mitaial Review Board W, Hapad, CA. Cane to the FOWL Wk- sbp at 1o:oo dm and stay on. Bill Ragsdale Dave Bculton Kim Harris John James -9e Claverick

!XRlW DIWICFLS solicits editorial mterial, COrmentS and letters. Eb responsibility is assured for accvacy of ilklterlal SUbnltted. 4LL MAERL4L PUBLISHED BY THE FCRIl4 IHPEREST GWP IS IN THE PUBLIC DOMAIN. InfOrmdtiOn in FatTH DIllZLJSICNS my be reproduced with credit given to PUBLISHER'S COLUMN the autha and the Fath Interest Qoup.

SUbScriptiOn to FORI'H DI-IW is hee with nenbershlp in the Fath Interest Qoup at $12.00 per Far ($15.00 . m't let yw membership in FIG crash. &new today! merseas). Fcr membership, change of adhess and/a to It's easy. Just send in yw check for $12.00 ($15.00 =hut material, the address is: ovecse~)and p'11 be all set fa the next s1x issues of pu(n DLIIPISICS and the FIG mtices. If you are in dwbt Fath Interest Qoup as to whether your membership is up, just look at the P.O. Box 1105 address label. If it reads "Renew March 1980' then its San Caclos, CA 94070 tiae to get that check off. D3 it today. The next issue of FORTH DIMENSIONS is going to be super. It will be a teclnical issue with all tk. entries subnitted in the Case Cmtest. We sure that you receive this inpatant issue, renew yw nertership in FIG today.

HISTORICAL PERSPECTIVE This my sound like a hard pitch for your membership hut PIG needs you. lte cnly way that we can keep m plblishirq Pccrm DWENSICS and qeading the FORRf wcrd is by having 'yar a;lppcrt. In fact, haw about getting others to sign KRlli ws created by W. Charles H. nace in 1969 at ehc rp. Matiara1 -10 AstroMmy Observatay, ~lott,eSVllle, VA. It was created out of dissatisfaction with available poqramurg tools, especially for cbervatxxy wtcamtion. rpu -tens It. nDQe and several associates famed m, Inc. in 1973 fa the purpose of lic~~ingand suppot-t of thc CORM Oprating System and Frogranaing Language, and to wly awlication pqranming to meet c(~lb311cTs unique require- mts . KIM HARRIS COURSE

Ik Path Interest Qorq, is antered UI Natharn Cali- falUAr alVPuqh Ouc errhipOf 1100 iS eld-dd.. It A five day interuive mwse m gzqranming with FtXlW was fadin 1978 by PDRTH poqranrecs to enowage ua d will be held July 21-25 at Hurabolt State University in tb language by the interchange of ideas Urough dnrr Arcata, California. "he course will cover thc PORTH ud prhlications. rlp~roadr to wcducing canplter applications includiq: (1) ~yulyzinqth requirennts of a woblm, (2) &signing a logical aolution, and (3) impleaenting and testing the mluticn. lbpics will include the uaagt, extenion, ad internal8 of the FORTH language, compiler, assembler, virtual mine, wltirasking cperating wtem, mass stam IMPORTANT DATES virtual EY manager, and file system. Colprters will be available for demonstrations and class exercises. The CoULse will be taught by Kim Harris, and Humbolt State ryXil 26 PIG Monthly Meeting, 1:00 pm, at Liberty fhiversity will give 4 units of -edit though the offie of b&?e, Hapard, CA. to th loAlL Wak- Cartinuing mtion. Nition fa the cxxrse is 9112 per shop at 1o:w &a and stay on. stant. ?he wxt will be "Using FORlW: ropics will be available at the cars fa $25 each. Harsing is available hY20 National FIG Meeting, Disneyland Hotel, in very nice dcrmimy room8 fa $9 per person per night a .Anaheim, CA at the NCC Personal Caputing at several =by notels. Cafeteria meals may be prr* Festival. Dimin the evening and technical individually a at $10.25 per day. Ftc me informtim acssions all day. Contlrt: Jim Plarnry, and regisPation mtecials vrite, befae Jvle 23: (408) 779-0848. Rof. mldWmit May 24 FIG Monthly Meeting, 1:00 pm, at Liberty Physics Departwent Hcuae, Hapard, CA. Caa to th? RIIlLWak- nubolt State University shop at 1o:w dm and stay al. Arata, California 95521

Page 1 Fo#IH DIMENSIOESS II/1 FORML NEWS Camittee -ka&r netapoRIH - Nucleue kwrd -a TI7 Inc. 555 Rl Ry A=. Suuryvale, CA 94086 (408) 735-8080

FOWL (FORTH Modification Laboratory) 1s d research Ccnctrrency, Multitasking, mry Ilolma TOY,madinating individual effmts on the technical Executive Ccranication 808 Colemn, 121 ewlution of m. Waksbp mectlngs Be held the forrth synckon i zat ion knlo Pgk, CA 94025 Saturday of each mth at 1O:OO a.m. at the Liberty House, Hayuacd, UI. (Hake a day of it by staying Em the FIG seings John -saay meeting in the afternoon.) Working groups determine 11 HiramDnte R3ad and docunent: the ob]ectives (hat pxblems need to br &in&, CA 94563 solved), status of topic (what has already becn &re), (415) 254-2398 tk challenges (hat has to be done), the mpthods (th appropriate approach), the list (detailed topics and -tat ion Jotm S. J-8 problems), the specifications (requirements of valld P. 0. Ba 348 so1utim.s). You can input directly to the technical Berkeley, CA 94701 aamittees cr to FIG Chaicmn Kim Harris (see Files -1. (415) 526-8815 We wittees ad leaders are: CYaphics Hanard Fecarlmttm 1055 Ctegcm Ave. cam1t tee Pal0 Alto, CA 94303 (415) 8S644M Nmeric Extensions L bFXK StuKt Floating mint P.O. Box 1418 Piles OBllS Kim Win Sunnyvale, CA 94088 1055 Oregon Ave. (408) 296-6236 Pal0 Alto, CA 94303 (415) 85644%

FaRML needs your help. Cane to the next meeting1

THIS IS THE BEGINNING! THE BEGINNING OF FIG TWO! THE BEGINNING OF FORTH DIMENSIONS 111 IT’S TIMTO RENEW! RENEW YOUR+1YIYI)ERSHIPIN FIG! RENEW YOUR SUBSCRIPTION TO FORTH DIMENSIONS! DO IT ALL FOR ONLY $12.001 00 IT TODAY! W.8 M8.W CHECK THE LAIaL IOR RENEW DATE! IF IT READS “Renew Mar. 1980” SEND A CHECK!

SEND IT TO: FIG, P.O. Box 1105, San Carlos, CA 94070 RENEW NOW!

FORTH DIneSSIONS II/1 Page 2 FORTH, for the Motorola 6809 Inside a word, one may use X and D without bothering to save their values on entry. If one wants a second index register (very handy for =me- thing like (EIOVE), then one or mre of Raymond J. Talbt, Jr . Y, S, or 0 registers may be swed in 7209 Stella Link, Suite 112 memory (or on one of the stacks). Houston, Texas 77025 Before listing the code which makes the FORTH machine, let me describe the 68'FORTH is an implementation of notation used to make dictionary fig-EWUH for the 6809 microprocessor. entries with the TSC assembler P4KXO It is available on 5" disk configured facili ty: for an SWTPC SS-50 Buss system with Swrpc MF-68 dual 5" disks and the TSC FLEX 9.0 disk operating system, but it is easily modifiable for other systems (write author for information).

The 6809 is a greatly improved version of the Motorola 6800 8-bit microprocessor. It is almost like having a 16-bit micropocessor, since there are several 16-bit instructions. It has two 16-bit index registers X and Y, and a 16-bit accumulator register D A-I0 which may also be used as two 8-bit The &n quantities refer to parameter registers A and B. There are many to the MACRO. E.g., addressing modes , including indirect, autodecrement, and autoincrement. MACRO 4,BAS,E The two hardware stack registers will assemble as make it ideal for F'€)RTM - it is almost a FORTH machine in silicon. I have 84 42 41 53 C5 LI NK implemented FORTH by the following register assignments : Where LI NK is the link address to the previous entry. This macro coupled The FoIiTH variable with assembly of addresses allows one Stack - u stack register to write code that is essentially just colon definitions, The EDRTH return e.g., the macro definition of COLON Stack - S stack register itself below. The EDR!Ili in- Here is the assembly language str uction listing for the portion of the code pointer (IP) - Y index register which defines the 6809 FoR!IFl machine: The FORTH register W (which points to the machine code being exe- cuted) is never stored (to save an instruction which is usually unnecessary) , however , upon entry to a word's machine code, that address is in the -- X index regis ter

A-11 Sane arbitrarily chosen examples of be read or written in lieu of the the great economy achieved by this use termiml. (The wurd READ switches KEY of the stack registers is given by some to read a text file, similarly WRITE words shown here (note: depending m switches EMIT to write a text file). location, some of the BRA have to be Consequently, it is possible to com- the long branch instruction LBRA). municate data between FORTH and other FLEX pxograms (Horrors - BASIC even!!). 7, LXDI3r.E '.2 '.2 X Another feature of 68' FORTH is Krn something which should be part of any l..'..: FORTH system which operates under a D host Do5 - It has a mrd (underscore .v on some terminals, 1eFt arrow on Krr others) which is followed by a text 2.1.. *+2 string (delimited by carriage return or .ti 'I double quote). The text string is Rm) I..( passed to the COS mnmand processor. -2 ',a1 While in 68'lW!"H one can do any FLEX Rm) I,.! e.2 command, e .g., C.\T (catalog of FLEX 1.0 files), DELETE, etc., by, X.D RENAME, .x e.g. Krr 2.,.R s.2 D plll Cop Item hm vx. atMk - CAT l.F (carriage return) D plsh Onto ret. sack bExT to get a catalog of all files on drive These various fragments of 6809 1 with name starting with F. This type code can be compared with the cor- of facility is extremly useful for the responding 6800 code in the FIG 6800 exchange of data with other types of ASSEMBLY SOURCE LISTING. Specifically, programs and for using FORTH in time- the 6809 NEXT routine takes 14 machine sharing systems where other pople use cycles whereas the 6800 NEXT routine other languages. For example, at Rice takes 38 cycles. we operate a PDP-11/55 with the UNIX operating system and FOR?H functions as The 68'FOR"Y implementation for the just one time-shared process along with 6809 is essentially identical with the many others. As yet our PDP-11 €T3RTH 6800 fig version except for the machine does not have this word, but I plan code for the mds defined that way. to include it in oraer to take advan- Many wwds which me coded (like PLUS) tage of the many extremely useful are shorter in 6809 code because of utility programs which exist in UNIX. the 16-bit math. For all of the In particular, in that environment, we colon-definition-like-words in 6800 want to be able to transfer data fig-FORTH, I just used my WRDd MACRD; between tapes and disks as background that keeps the source file short. jobs while we are wurking with files interactively with FURTH. Also, for 68'FORTH implements the full nufilber crunching work, other languages fig-FO#M vocabulary as given by the are more convenient and faster than May 1979 6800 ASSEMBLY SWXE LISTING FWt"H, so te plan to implement certain and the fig-FORTH Installation manual. tasks in other languages to be done as In addition, particular installation background jobs supervised by UNIX dependent code for EMIT, KEY, and disk while we use FORTH for just those read and mite are given for a 6809 interactive tasks for which it is system with all disk 1/0 being done ideal. via the disk sector read/write routines of the TSC FLEX 9.0 disk operating My main reason for pointing out system. FLEX formatted text files may these FORTH mnnections to another Dos

POKIH DIMENSIONS II/l Page 4' is to encourage the FORTH standards team to think about standard vocabulary wads far these links. FORTH grew up and still largely exists as a stand alone operating system. However, already it is used in some places as simply one language in a multi-language time shared system. I know of two places -- here at Rice where we have begun a rudimentary connection between FORTH and UNIX, and at Kitt Peak Na t iona 1 Obser va tor y where the ir CIX 6400 has very elaborate inconnections between FORTH and CDc's SCOPE.

Editors Note -- This is an excellent example of conversion of a FIG assembly listing to another processor. However one me change is in order. NEXT on the 6809 is only 4 bytes long and the code jump to NEXT takes 3 bytes. On processors this powerful, the code far NEXT is repeated, in-line, wherever needed. This costs one byte but saves 3 clock cycles on each interpretive cycle. The time overhead of indirect threaded code is then 12 cycles. Similarly, PUTD should k expanded in line. Recursion - 2he Pan Queen Problem at hand finds the board KOw and ClOlUar locations on The Eight Queens Problem llJhich eight &ss queens would be safe from mutual attack. This example Jerry kVan doesn't check for board rotations 011 Dept. of Math Science reflections, so more answers are Eastern Kentucky University Finted than necessary. Richmond, KY 40475 The output gives the calculation nLrmber on which the answer was found The Eight Queens problem has been and a list of the eight row nuntms, often used as a textbook problem in aolunn by colunn on which the queens pxgrming, particularly to illustrate are located. Now it's your turn to recusion. I present here a solution in DO-IT. mm.

Recusion is the technique of 8a I 57 0 ( 8 qwans by Jerry kVan UIR-7)DLcOZ ) allowing a procedure (a FORTH word I : 1. W? + ; ( double s velue ) 2 definition) to call itself. This 3 : UTSLL? ( allw a word to call itself. by rscurslon ) 6 UTIST WA CFA , ; Imamti is normally blocked during FORTH 5 ampilation, to allow a old word nane 6 : IABlAY ( ukas an array of 1's. ss given by lnput ) 7 <8UIu)S 0 Do I , LOOP to be used in a new definition of the 8 DOES> SUA? 2. + : ( leave sddresa rirhln artmy ) 9 same name. For example: LO 8 I*u*T A ( these form uorkspece for the solutions ) I1 16 IANAY 8 I? 16 UIMT C :HEW CR CR HELP CR ; I3 8 IAlMT X ( [him COntaiM trl.1 solutions 1 CR lb -> 15 The new definition of HELP will execute a previous definition, but with two carriage returns before and H1 I 5a after. This is a necessary and camm 0 ( mre 8 queau vII-790Lc02 ) capabi 1i ty . 1:SAn z syu ovp om ovm OVER 3 -7+C@>R b +B@H How then to have a word call itaelf, 5. DIor A @ u I> ; 6:"K if not by name? The answer is MYSELF. 7 syu oyp OVLI ovm om This word will compile a call to 8 -7+c OSUA?! the 9 +IOsyuI word in which it is located: LO MO?AONuI; 11 : pI(Iu 12 sw om om oyp ovm 13 -7+CISU?I : DEMO 1b +8IsyUI 15 MO?AIWUl;->

IF MYSELF EISE - -: In this example, if the test is true at IF, at MYSELF a call to Daro will occlnr. This is acamplished by defining MYSELF as IMMEDIATE. At compile time, MYSELF executes and compiles the execution (code field) address of the mst recent (actually incarplete) definition in the CUFWNT vocabulary. The fig-- definition is :

: MYSELF IATGST PFA CFA , ; pMEDI#pE A 'TINY' Pseudo-Code Bill Powell Sawbr idgewor th, Her ts England

There are some interesting speed/ nucleus OODE routine. This is done by memory trade-offs which depend on the a look-up table which m6ts two bytes pseudo-code adopted in implementing per entry just as the Code Address FORTH. The discussion by David Skag rrormally does. We can suppat up to (11 for the PDP-11 shows 17Iy: to be both 64 CODE routines this way. Despite faster and more compact, but less the time taken for bit testing this flexible (?) than ITC which is the structure works out quite fast because de facto standard. But 6502 FORTH only one byte has to be fetched. Of (Program Consultants) appears to use murse we could arrange for methan the JSR/RTS structure. This is 64 03DE entries by defining one that faster, but must lead to a lot of code gives acoess to a three byte structure, since it now takes 3 instead of 2 bytes but 64 should be enough. to reference each low level (CODE) routine in a high level (COLON) The effect of these one byte definition. instructions is to make the body of COLON definitions much smaller. On my 6502, an 8 bit machine, it Literals require 1, 2 or 3 bytes seems attractive to call the most instead of 2, 3 or 4 bytes. On the frequently used FORTH words with a other hand ~ISTA"~and V.4RIABLES will single byte. My 'TINY' code reads the usually require 3 instead of 2 bytes first byte and then shifts it left to since in TINY they are compiled write bits 6 and 7 into the sign and like Literals. But these words are carry flags. For codes $80 thru $FF infrequent in FORTH because pataneters (carry set) a branch is taken to a 2 are passed on the stack. byte COLON instruction. The even vale we 1l0w have is used for the b byte for the Instruction Counter (IC). The Hi byte is read by the original IC before being saved on the return stack. This is still a two byte pcode which allows us a vast number of Colon definitions. But we no longer need the Code .Wess, saving 2 bytes. But we must start these entries at even addresses which will cost 1/2 byte on average.

Next the sign bit is tested. If clear, a txanch is taken to a routine for low Literals which pushes the numbers 0 thru $3F on the stack. Then this routine drops back into the 'TINY' interpreter. These low literals (0-63) thus compile into fast single byte pcodes. Frequently used Variables can be stored at these memory addresses making this doubly useful, e.g.8 user klf Variables . For codes $40 thru $7F the above branches fail and we drop into a

Page 7 Fo#RI DMEHSI- fI/r The table above analyses three fams An impartant aspect of is the of overhead: acoess it gives the user to the struc- ture of the language. Therefore I 1. Time overhead in cycles would still like to gee rpc remain the weferred farm because of its elegence 2. Dictionary building and flexibility. But TINY has Rlllch to overhead d .bytes offer on -11 8 bit systems. 3 P-code required each (11 Skag, D: “IYlC v/s rIC far FOmm time the entry is KRI9 D-1- Wl- 1, Eb. 3, called pabytes NOV. 1978 Sections 1, 2 and 3 analyse EOKEi words of type OE, COLON, COFSTNW, and Section 4 analyses Literals. In Section 5 we find the time over head to execute a line assumed to contain 6 CODE, 1 Literal, and 2 Storage (CONSTANT) words, as well as the space far its pde. Sane of the num?rals have been assumed low. Section 6 is like Section 5 except RENEW NOW! that 3 of the CODE words have been replaced by 3 COIDN wocds of the type in Section 5. At this level we can get a good idea of comparative speeds of RENEW NOW! execution.

Section 7 gives the storage required RENEW NOW! fa a program of 35 CODE, 20 stacage, and 60 COLON words (drawing equally from Sections 5 and 6). This does not include the space for actual data ntx fa the machine code of the nucleus, but does include all p-code and dictionary overheads apart from the haders. Taking XTC as 100% we see that the performane becomes: -TINY JSR/RlS an: Time Overhead 78% 66% 89% Space €&@red 66% 103% 104% The benchmarks are for the 6502, but similar ranking seem likely fa other 8 bit micros. Clearly, longer pqrams will favor TINY even more. On the other hand JSR/RTS may execute even faster than indicated because the nucleus can lMke freer use of the cpu registers . FORTH in Literature

At the E'ORTH Convention, October, operator indicating his interest and 1979, Dan Slater gave a shart report on approval by operating any terminal key an experiment on communication with at the REST after each stanza. killer whales. By use of a touch sensitive plate, the orca could learn to physically equate touching a posi- tion with a concept or object. Interest was expressed in using the syntax of FORTH to define new items. sca I I08 0 ( The Tbry that Jack bullt yR-))DECI5 ) By this method a man/whale vocabulary I ( From The Space Child's Mother booe. Irdrlck Ylluor ) 2 : ICCITE I10 LO? pU1: ; ( say this pou ) can be built. 3 : TUC . the ; 4 : THAT W .* nat " ; 5 : TUlS CI .* Thl. 1. " rn i The evening Charles Moore read a 6 : JACK ." Jack built" ; ? : sumany .*Suury" ; FORTH poem by Ned Conklin. It is 8:W .* Flau" ; based 9 : lRlllluI .' Ihl.rry" ; loosely on a classic of English LO : K ." hutant K" ; literature. 11 : WE ." Lrudlta Verbal Yaae" ; 12 : ttIlAsL .* Turn of ?leuslble Chrad' ; 13 : BLUFF .' Chaotic ConfuDion and Bluff" ; Cybermtics :9)K; 14 : SMF ." and Stuff" ; : my boty JACK ; --> SIxPEIlcE ! IS ." BEGIN WE @ poCI(ET +! rruLL 24 o ID BUCIBIRD I + e PIE +I w FAPZ BCGIN X3OPDIED SIX MIMY-DISH KItC ! SURPRISE ;

A-21

Bill Ragsdale has submitted two me. This is a familiar quotation, with apologies to Browning:

: LOVE CR .*I How do I love thee?" CR ." Let me count the ways." 1 BEGIN CR WP . 1+AGRIN

: RHYME JXK DUP NIMBLE BE W QUICK BE CWLE-STICK OVER JUMP ; Finally here is an actual, full poem. It is taken from "The Space Childs Mother Goose" by Frederick Winscx, Simon and Schuster, 1958. It consists of eleven stanzas and is almst recursive. The first two screens compile the primitives from which the poem is recited, by loading of the last screen. The computer ' s recitation occurs stanza by stanza with the

Page 9 FORTH, Inc. News Virginia - Call Joel Shpentz (703) 437-9218 or Paul van der Eijk (703) 354-7443 Texas - In Houston, call Jeff A series of free seminars and paid Lewis (713) 729-3320, ($100-125) wurkshqps is being offered; in Dallas, call John plyFORTH will be presented. The Earls (214) 661-2928 and schedule is: Palo Alto, May 8 & 9; in Denton, call Dean Rxhester, NY, May 13: Boston, May 14 & Vieau (313) 493-5105 15; New York, June 10; Cherry Hill, June 11; Washington-Baltimore, June 12 Arizona - Call Dick Wilson (602) & 13; Houston, June 16 & 17; New York, 277-6611 ext. 3257 June 18; Palo Alto, June 24 & 25. For mxe information and/or to regis- Wegon - Call Ed Kamnerer (503) ter: Call Kris at FDRTH, Inc. (213) 644-2688 372-8493. NewY-k - Write Tom Jung, 704 166th St., Whitestone, NY FIG DOINGS Michigan - Call Dwayne Gustaus ~ (817) 387-6976 Intensive Short Course

The American Chemical Society is offering a nlnrber of five day, hands- on, in-depth lab courses on micro- PUBLICATICM processors and minicomputers. The participants will have access to a PDP-11 netwmk running KR'IIl. Sessions are June 8-13, September 7-12 and Dick Miller has sent the first issue December 14-19 at VPI, Blacksburg, of the M HR"H Newsletter. It's jam VI at a cost of $485 for JCS members packed with news, tips and updates fa and $550 for non-members. For more mS EOKRI users an the TRS-80. infamation contact ACS Short Coaxes, 1155 Sixteenth St., N.W., Washinglmn, It's a service to registered awners, M= 20036. and Dick would be glad to send a sample copy to prospective users. write Miller Services, 61 Lake Shore Road, Natick, MA 091760. * * FIG GKIUPS OR FORMING Thanks to Fig member Frank Dougherty (325 Beacon Street, Belvedere, IL San Diego - Call Guy Kelly (714) 61008) far the miteup in the Blackhawk 268-3100 ext 4784 01: Itxu Bit Burners Newsletter. Frank dis- Boyle (714) 571-7711 cussed the language and ocp: efforts, as well as the dialect STOIC. Seattle - Call Dwight Vardenbvg (206) 542-8370 a Terry FURl'fl for Micr-ers by John S. Dettman (206) 821-5832 James originally published in Dr -Dobbs Number 25 May 1978 has be= Mass. - mird Wednesday at 7:OO repinted first in ACH SIBIAN NXICES, pm in Cochituate, MA. Oct. 1978 and naw in an IEEE Tutorial: Call Dick Miller (617) 653-6136 SUPPOEZT, IMSONG LEE, EDImR, IEE cat solution. Topics will include the No. EHO 140-4 to quote from this usage, extension, and internah of the publication "James gives a compact, but FORTH language, canpiler, assenbler, not necessarily easy, introduction to a virtual machine, multitasking operating stack oriented, interactive pxqramning system, mass storage virtual memory language called FORTH. A better manager, and file system. Canputers tutorial presentation may be found in will be available for demnstrations the manual, PKXRAM FORTH, A PRIMER, by and class exercises. The ccurse will Gregg Howe, Steward Observatory, be taught by Kim Harris, and Humbolt University of Arizona, 1973." The State University will give 4 units of current availability of this document credit though the office of Continuing is unknown. Education. Tuition for the course is $112 per student. The text will be "Using lXRIfiA; copies will be available at the course for $25 each. Housing is available in very nice dormitory rooms More on STOIC-I1 for $9 per person per night or at several nearby motels. Cafeteria meals Technical Report TR-001 may be purchased individually or at $10.25 per day. For mre information "EDIT79, A STOIC-I1 Programming and registration materials write, Example" (63 pages) $7.00 before June 23:

This report represents and example Prof. Rxmld Zammit of a non-trivial program written Physics Department entirely in STOIC-11. The program, Humbolt State University a text editor, was cross-ampiled to .Arcata, California 95521 produce a stand-alone object program, thus facilitating benchmark cwnparisons with the CP/M editor which it closely resembles. Included in the report are the benchmark results, a txief user's guide, and source code for the editar along with extensive cements.

Contact: Jeff Zurkaw Avocet Systems 804 South State Street Dover, DE 19901

RENEW NOW!

KIM HARRIS COURSE

A five day intensive course on programming with FOWH will be held July 21-25 at Hlrmbolt State University in .&cata, California. The course will cover the FORTH approach to producing ccmplter applications including: (1) analyzing the requirements of a prob- lem, (2) designing a logical solution,

Page 11 EolzTH DYMEISIOkS II/1 NEW PRODUCTS

Heath H89 and H8 FORTH for the Heath 89 and 8 is possible with the fig-FORTH 8080, t iny-FOKlX Version 1.1 (as demonstrated by Jim Flourmy at the January FIG meeting). A version of fig-FORTH tailored to Walter Harris implemented and bought the TRS-80, Level I1 with 16K bytes of up the code on his dual disc H8 and lnemory minimum. I/O devices supported reassembled it for the H89. For me are : keyboard, display and cassette information, contact: mR!RI PakFer, P.O. tape recorder. New words can be Box 2455, San Rafael, CA 94902. defined to control other devices. The editor is identical to the fig-mr?IFl editor and the output format is modi- fied slightly to fit the TRS-80 display. Documentation includes : introduction, editor, graphics, assembler, advanced tiny-FORTH and Source Data Systems announces a applications. The style is tutorial language for non-programmer data with hundreds of examples that teach definition, transaction definition, tiny-€YIRTH in a hands-on mde. $29.95 file definition and report generation for tiny-FORTH cassette and full far Honeywell Level 6 Minis. Designed documentation for the Level 11, 16K for infarmation management and retre- TRS-80 plus $1.50 for shipping and vial when used together is SE's Soure handling ($5.00 outside the US). The Data Entry package. Far mre informa- Software Farm, P.O. Box 2304, Restan, tion, contact: Source Data System, 208 VA 22090. 2nd Avenue, S.E. I Cedar Rapids, IA 52406.

KIM-1 FORTH AMD 2901 FOKIH PIlDcESSOR This version was written fran the FIG model by Ralph Mane of Vancower, Rnctional Automation unleashes the Canada. It contains a complete 1/0 thing, a FORTH based front end programing system which has an inter- processor far its AMD 2901 based 64 bit preter/-iler as well as an assembler wide microprogranmd mnputing engine. and editor. All terminal 1/0 is The system pqramning language is FASL funnelled through a jump table near the (Functional Automation System Language) beginning of the software and can which is available users. For more easily be changed to jump to user- information, contact: Functional written 1/0 drivers. 6502 FORTH Automation Inc., 3 Graham Drive, resides in 8K of RAM starting at $2000 Nashw, NH 03060. and anoperate with as little as 4K of additional mtiguous RAM. $94.00 for 6502 FORTH system on KIM cassette. $16.50 for 6502 FORTH user manual. Eric C. Rehnke, 540 S. Ranch View m1c Circle, 161, Anaheim Hills, CA 92087. mIC, essentially an extension of m, is a general purpose interactive

EOR!lTl DIMENSIUG II/l Page 12 pogram, assembler, debugger, loader and tutorial for FORTH language. and operating system within a single Information is available for recon- consistant architecture. With core figuring to interface with other disk efficiency and high running speeds, -ratings systems. the language is extremely flexible permitting the user to develop a FLEX 9.0 format 5" disk pius working vocabulary of subroutines documentation: $39.95. tailored to specific applications. Talbot Microsystems The entire package, including a 7209 Stella Link, Suite 112 library of predefined subroutines, Nouston, TX 77025 is copyrighted but available to educational users, STOIC requires three discs, two are SlOIC itself and the third contains a bootstrap that permits the entry of STOIC through CP/M P~~ RELEASE and the mtinued use of CP/M disc 1/0 under STOIC. For more information, contact: Steven Burns, Massachusetts 8080 Assembler Available Institute of Technology, Room 20-119, Cambridge, MA 02139. John Cassady, who did the original fig-FORTH 8080 listing, has now re- leased an 8080 FORTH assembler. John's assembler handled all Intel mnemonics and can easily lx altered to zilog, as it is published as source code. It 68'FOEITH FOR 6809 handles structured assembly condi- tionals IF, ELSE, THEN, BEGIN, UNTIL, WHILE, and REPEAT. It is integrated with the FIG security package to verify 68'FiIR"H is a 6809 implementation axrect structuring of conditionals, of the EQR"H Interest Group standard during assembly. John provides for vocabulary of this powerful language. named subroutines as well as CODE definitions. 68'FORTH consists of full FORTH Interest Group standard (May 1979) Send $3.25 (includes postage) to vocabulary with names to 31 characters, John Cassady, 339 15th Street, Oakland, 16 and 32 bit integer math, compiler CA 94612. error checking, and source text editor. System is supplied with additional vocabulary to simulate disk in memory (useful far modifying to wark with other disk systems or enabling polyFORTH-CP/M is FORTH Inc.'s cassette-only operation), to use disk polyFoIiTH, interfaced to run on nearly fat virtual memy (allows large data any 32K a larger CP/h based system. sets to be used in small memmy), to When loaded, polyFoRTH-CP/M finds and interface with FLEX 9.0 text files for links-up to the CP/M 1/0 drivers, input and output, and to perform initializes itself, and responds "up" standard FORTH disk block read and on the system console. At this point, write. System is supplied on 5" floppy true plyFORTH is running, that is, disk configured for SWTPC MF-68. FORTH structured ( screen oriented ) Minirmnr memay requirement is 8k ftx diskettes must be used. It is impr- FLEX plus 12K of user space. Docu- tant to realize that polyFORTH-CP/M mentation contains description of all does not run under CP/M, it runs in vocabulary words, information on place of CP/M, utilizing only the CP/M configuring for individual system, I/"o drivers. The pOlyFORTH-CP/M System, as 8080 fig-FO#IH supplied by MhB DESIGN, is a Value- sapcae Listing ...... 10.00 added system. Inc.'s canplete 8080 polyl3XTH system- is supplied, plus Installation Manual an additional diskette and manual (F.I.G. Hoael) ...... 10.00 containing interface material. Also provided, is a CP/h utility that allows (CA residents add 6% tax) transferring polyFORTli blocks (screens) to a CP/h file, and transferring a CP/M file to p0lyE'ORTH blocks. Saace is Write: Jeff Fox (415) 843-0385 supplied for the entire plyFORTH 2223 Byron system, the polyFORl!H-CP/M mmponents, Berkeley, CA 94702 and the transfer utility. polyEWTH-CP/h is available directly from M&B DESIGN for $4,000 on a wide variety of diskette formats. Contact:

ANCON provides a wide variety of M&B DESIGN FORTH products, including: Hobby 820 Sweetbay I2. versions; TRS-80 Cassette, $29.95; Sunnyvale, CA 94086 Heath H8489, $49.94; 8080 CP/M 8in, (408) 243-0834 $49.95: 6809 5" Flex, $49.94.

Personel sys tems ; TRS-80 Tape 8 $45.95; Disc, $65.95; 8080 CP/M 8" $125.00; pdpll, $140.00; NarthStar, FQRTH for Foly-88 Wcropolis. Commercial/Industrial/Scientific versions available for specific fig-FORTH for the 8080 as imple- requirements. Jim Flournoy, ANCON, mented by John Cassady and modified by 17370 Hawkins Lane, Morgan Hill, CA Kim Harris is now available for the 95037, (408) 779-0848. miy-88.

This version uses cassette and ram simulation of disc, and includes full use of upper and lower case characters as well as the Greek character set, as well as high speed graphics. .9n editor and an assenbler are included.

The amplete RENEW NOW! system price is ...... $50.00 FOKTH on cassette (needs 8K RAM 2000-4000H) . 25.00 Poly-88 Fath User's~~ide...... 10.00 LETTERS -- the limitations of the traditional approaches. LYON'S DEN March 14, 1970 [Editors note - George Lyons has ax;esponded on FWTH topics over the full life of FORTH DIMENSIONS. He George B. Lyons addresses technical and philosophical 280 Henderson Street topics. We're formalizing his con- Jersey City, N.J. 07302 tributions into a bylined column. Welame to the Lyon's Den.]

I suspect that a paramount issue in decisions on whether to use FOR!L'H or Rogrm was nice enough to supply another language is a tradeoff between me with a reassembled version of their language convenience and compiler Apple-FORTW Kernel plus screens of the cnnvenience. By implementing a complex dictionary entries fur my KIM-1. This syntax a PASC-U mmpiler, say, auto- was all entered by hand, painfully mates part of the programing task at debugged, editor programs written (in the expense of a time-consuming source their FORTH), etc. I then tried to entry and processing operation. duplicate the "PI" routine in the Ik.

Standard ~~ seem to be at the other Dobbs Journal, only to find that extreme, leaving me explicit details Rogram~didn't carry extra bits of to be coded by the programer, for the intermediate accuracy in the multiply gain of easier processing with an routine. Then another week of spare interactive resident compiler. time (midnight oil) work to rewrite the math routines to allow "*/hOD" to work The polarization of FORTH and its properly. It finally worked. alternatives on this scale may only be due to the absence of standard FORTH I'm not bitter tbugh. "hrough all vocabularies to provide the same degree of this I learned enough of FOFU?H-liks of automation traditional languages programming to be more enthusiastic supply. I wonder if a quantum jump in than ever, but disappointed that the EORTH's popularity would result fran example programs I've received from supplying for traditional you are not usable by the Programma languages implemented in FORTH. version. I am therefore eagerly Possibly, transparently obvious FORTH awaiting the availability of the 6502 language features could be provided version of fig-FORTH for my KIM-1. achieving the same results. areas where the greatest inrpact might ame are PASCAL data structures, ALGOL J33ard J. Bechtel, M.D. procedure argument passing and dynamic Newpat Beach, CA local storage allocation, and APL matrix alge&a. If techniques for these operations in FOKIli were widely known no one would Should you have any books, manuals make the mistake of referring to RXI'Ii cc other documents pertaining to FDKIY as a species of mamo assembler. By which are available by special cxder, I demmstrating that traditional language would like to have a list. There seems convenience is available in KRTH users to be a real need for textbooks or might be motivated to take advantage of tutaials which will carry a user fran the extensibility of F"H to go beyond the most simple FORTH constructions to the very elaborate ones like (BUILDS and DOES>. (See x1 below.) For your information, I am working Fditn.. . with the mnsFoRTH implementation from Miller Microcomputing Services. I am "k nhrs left on the stack after quite satisfied with the system to an error are the block number and date, and look forward to other exten- character offset. See ERROR. This sions. I have distributed several allows WHERE (Scr88) to display the "H programs to MMS which they may of fending text . use in their newsletter. Should the FORTH Interest Group have a program exchange or plblish programs, I will submit these programs to you also. (See #2 and #3 below.) Thanks to John James and FIG, I've upgraded my sub-FoKtfl to what I now call 2650-FoURT€i. To date, except Andrew W. Watson for the disk 1/0 verbs, my FORTH mre Vinton, VA a: less mtches Mr. James' FORTH with the exception that I've incorporated an Editor.. . assembler, it's fully KIM based and it has a few more primitives. I do #I - Use the Mail Order page and see support a cassette IF but can't use Information and New Products the full power of the fast virtual sections of FD. storage. I will release a copy of my 2650-FORTH to FIG as well as any #2 - Send programs to FD! application work that I've done. #3 - Address for Miller Micro- computing Services, 61 Lake Myself being broadly classified Shore IZDad, Natick, MA 01760. as a computer architect or computer designer, I have a very keen interest in turning out a FORTH engine (to borrow a phrase from Western Digital), and will attempt the implementation. I I want to tell you how iqressed I am will potably use the 2900 series bit at the quality of the Installation slices since I have all the developnent Manual and the 6800 Assembly Source tools. Is there saneone in this vein Listing ! that I could contact?

The 6800 listing provided everything I needed to build an identical source Edwrd J. Murray file. The Symbol Table and hex dump Pretoria, mion of South Africa were especially useful in tracking down the last small typos. (I used the check sums for the 'Sl' dump to locate Editor... typos such as INS instead of INX.) Tb get FORTH running on my system, all I Look forward to receiving your did was to modify the KIA address and 2650-FORTH. Adckess for John S. James, delete the coding for Tram. P.O. Box 348, Berkeley, CA 94701. I notice a peculiar behavior regarding the stack. If I type . when the stack is empty, I get an error message, as expected. But after the I was sanewhat disconcerted when I error message, there are two numbers on read the article by Mr. David J. Sirag, the stack. Is this normal? "DTC Versus ITC for FORTH on the the PDP-ll", EORTM Dimensions, Volume 1, No. 3. The author has, I believe, Gordon Stallings misunderstood the intent of the article Bar tlesville, OK byMr. Dewar. In Mr. Dewar's ariticls, the definitions of direct threaded code reveals that their techniques are (MC) and indirect threaded code (IW) logically identical to Dewar's 1°C. are : They have simply, through clever programming, taken advantage of a "DTC involves the generation particular instruction set and archi- of code consisting of a linear tecture. It is beyond the scope of list of address of a linear list this letter b prove this equivalence, of address of routines to be or to suport the FIG desire to have a excuted .'I mmn implemntation structure for all versions of FIG FORTH. "ITC.. .I' ( involves the generation of code consisting)"... of a Please note that I am -not quiblinq linear list of addresses of wards over semantics with Mr. Sirag. A11 which contain addresses of definitions are arbituary. (Hawever , routines to be executed. " the value of a definition lies in its consistency, precision, and use- As applied to the FORTH type of ability. I find Mr. Sirag's definition hierarchial structure (hierarchial of MC and ITC to be inconsistent with indirect threaded code?), I would the environment in which he operates, extend Mr. Dewar's definition to FORTH, and thus quite useless.) My be: intent is two fold: (1) I am a self- appointed defender of the excellent "ITC involves the generation of work of Mr. Dewar, and (2) I want to code consisting of a linear list cancect any misconceptions concerning of addresses of words which this issue for readers of this news- contain addresses of routines to letter who did not have access to be executed. These routines may &war's (better) definition of MT and themselves be ITC structures. " m. However, Mr. Sirag based his axclu- sions on the following loose defini- Jon F. Spencer tion : Sherman oaks, CA "The distinction between DTC and rrC as applied to FORTH is that in IYTC executable machine code is expected as the first word Many thanks to John Cassady for after the definition name; while, writing an excellent 8080 FORTH and in ITC the address of the to Kim Harris for implementing the machine code is expected." necessary mods. I received 8080 fig-FORTH Ver. 1.1 on 2 October Obviously, the two men are not 1979 and within a few days had the referring to the same things. I&. assembly langlrage source typed in and Dewar is referring to the list of assembled. A day or two later the addresses which define the RlRTH word, editor with a suitable patch for while Mr. Sirag is referring to the the M4TCH code was up and running implementation of the FORTH inter- along with the disk based long error preter. If indeed Mr. Sirag's state- messages. I[ have been learning and ment were true (which it is not) that gaining experience with f ig-FoRTH ever their "analysis contradicts the since. findings of mar", then they should have implemented a II1'c language rather After more than a year of using than the ITC language of FORTH! SrOIC from volume 123 of the CP/M Users Indeed, a careful examination of what Woup it is really nice to be using a is actually occuring in LABFORTH true ~~ that is consistant with the examples in the EORTH Inc. manuals and the several articles that have appeared With help from the Plodel I have now on ~ofi~~.I cannot over-emphasize how got to grips with the outer interpreter well documented the fig-FORTH system is and virtual memy system, and will be and how easy the system was to king getting together with Bill -11 and up. No bugs or errors have been other FORTH fanciers over here on an uncovered in nearly six months of cooperative implementation effort. use. Many thanks for your effort and The only thing missing from this creativity, which are not unapprecia- otherwise nearly perfect package is ted! the assembler vocabulary. Is an 8080/2-80 assembler vocabulary avail- able from the FORTH Interest Group or Bill Stoddart if not is any planned? If an 8080 15 Croftdown Fmad assembler is available or is planned a lmdon NW5, England short note OK a word about future plans in the next issue of FDRTH DIMENSIONS would be sufficient. Editor's note -- Bill had a marginal note to this letter: "certainly grows In any case I hope I get to see on you. This really is 'Computer some of you at NCC in Miiy so that I can Liberation.' BASIC was just a red personally thank you for making FORTH herring ." available to me.. . Sincere1 y ,

Do yw have a 280 version of fig- M. Paul Farr FDR"H3 It is not listed on your mder 2250 Ninth Street sheet but reading the text I got the Olivenhain, C4 92024 mession that you do. By the way, I have a tutorial paper Editor - discussing assembly programming in FORTH environment for both 8080 and Yes! An 8080 assembler is now 280. It is available, including source available in source code to canplement listing written in fig-FORTH, from 8080 fig-^^. Send $3.25 (includes KALTH microsystems. The price is postage) to John Cassady, 11 Miramnte $5.-G for 8080/85 version, $7.-uS for Road, Ckinda, CA 94563. 280 version or $10.-for both (add 15% in Canadian funds).

.Usof I am working on the assembler for the Intel 8086/88. If I knew that Many thanks for the fig-FORTH there are also other people interested installation manual glossary and lQm in it, that would motivate me getting Model, which have been difficult but it complete sooner. (It is a cross- enjoyable items of study since they assenbler that can be run on any FDm arrived a couple of weeks ago. based system.)

Like many of your mertlbers I became yours truly, interested in FORTH without having access to a EWI'H system, and gained my first wactical familiarity by using Kalman Fejes the lQm low level interpreter style K4LTH microsystems of linkage on machine code programs. P.0. Box 5457, Station "F" Ottawa, Ont., Canada Edi >r - accessing and manipulating data. Indirection, however, is only a Fig doesn't have a plan a 2-80 navagation technique for constructing version of fig-FORTH. We would be the address required by the hardware to pleased to publish a contributed implement OUT desired opration. When version, if as complete as the 8080 at the end of our circuitous logic, are Version 1.1 we then to complain "What can I do about this address".

Let's face it, @ and ! are perfect operators. .4s a participant in the Forth Inter- national Standards Team, I cast a yeah I value TD and its lmpllcations in vote for the inclusion of "TO" and its system structure. The procedures requisite definition of VARIABLE written using "10" are mre readable (though I prefer the name FIELD). than standard Forth, and result in Uthough I was first exposed to this fewer visits to NEXT as they are definition on Catalina Island, it executed. "To" will be included in any has many similarities to my own system I generate, together with other implementation of FIELD and RECORD. essential mds, which include @ and !. In its simplest form, as outlined by Paul Bar tholdi, FORTH DIMENSIONS As a Forth fanatic and a FORTH 1/4, integer variables of predetermined DIMENSIOS fan I sincerely hope that precision are defined to behave as the newsletter will continue. If there bidirectional constants. Normal is some assistance I can render please behavior is to push their stored value advise. onto the stack. A momentary, alternate behavior is to pop the stack value into their confines. This temporary Williams S. wry behavior occurs only when referenced 2700 Peterson Place, 153D after the word "TO", which sets a Costa Mesa, CA 92626 direction f lipflop. Thus

VARIABLE .A VARIABLE B Editor -- 10 'I0 A A'POB You're doing it! By thoughtful will place 10 into A and B without correspondence and participation in using the @ (fetch) and ! (store) group events people such as Bill are opera tors . multiplying OUT efforts. Each of us, who has implemented a version of 'TO"? encounters some exasperation in dealing with the addresses appearing on the stack. STRucrURED vARL9BLEs Since, in the prior illustration, neither A nor B supplied its address for TO'S execution we ponder the shortcomings of this newly offered FYom time to time at the Fig meet- definition and reluctantly sprinkle our ings the question of structured pocedures with @ and !. variables arises. This is a proposal for how they might be handled. FORTH is an elaboration on the indirect threaded list program archi- The December 1978 issue of com- tecture. As programers we are free to munications of the .4CM contained a add indirection to our methods of paper by John Backus on "Functional Programning" (also called variable free K"fi IN THE PUBLIC VIEW programning). I believe a variation of his ideas could be implemented in FO~.suppose we are given a pair of queues with bases at opposite ends of After the survey article in March available memory pointing toward each 15, 1979 Electronics, Mr. Robert other. Then enter an array into one of Gaebler wrote the usual letter to the them and begin processing it. Let the editor critiquing FORTH's postfix results go to the other queue as they notation. We are reprinting a well are developed. Multiple steps would stated rebuttal to this letter which alternate between the queues until a also appeared in Electronics. final result is obtained. These alternating queues can give some of the To the Editor: effects of functional programning (1) large state changes, (2) limited menury I want to reply to Robert Gaebler 's of past states, (3) no concern with letter on expression format in the garbage collection, 4) variables mt FORTH language [Electronics, July 5, named or declared. 1979, p. 61. Backus placed operators within the Gaebler notes, and I agree, that data. This could be done or not, as compilers can do the translation fran experience dictates. 'Ihese queues are infix to postfix notation and thus save not to replace the stack which FYXlTH the programer both work and the risk already has. ?he stack could be used of errors. Unfortunately, these to hold what I would call operator advantages are not available without variables m nrodifiers. sane penalty for extensible languages such as FORTH. If the canpiler is to Let us look at a couple of simple translate, it must know how to parse examples. Suppose we wanted to trans- expressions. The parsing rules for pose an array. 1 2 3 nimitive operators are supplied with 456 the compiler, but those for the added Enter it into one queue. (1 2 3 4 5 operators must be supplied by the 61. "Ype in the transpose curanand. 2 pogramner at mpile time, which makes 1 Tp. The 2 and the 1 go on the stack the parser much more complicated. so the transpose function knows what kind of a transpose is desired. The Examination of almost any program result will come out on the other will reveal that the majority of queue: 1425361 program statements are nonalgebraic OT can easily be converted to a non- Should we wanted to sum a vector. algekaic farm. Thus the advantages [l 2 3 4 5 61. Type in a reduction of infix notation, when present, OOlRILand. I + RD. The 'Tick' put the apply only to a fraction of the address of 'Plus' on the stack so the program statements. Far most function reduction function knows what kind of definitions, the prefix notation of reduction to perform. The other queue sukoutine or macro calls is required, receives the result: 21J and this can be replaced by postfix notation with little or no loss of clarity. W. H. Dailey 47436 Mantes Street Use of postfix notation l?aves E'remont, CA 94538 the parsing of all expessions in the hands of the prcgrananer . It means that arguments for an operator may be

I mFttT4 DIMiBlSI~II/1 Page 20 I -ed uslng the full pawer of the Fograring language, without any restrictions being imposed by the ~3.piler. With this freedom comes the xssibility of error, and argument $epxation is one of the mst error- xme portions of programming in a lalguage such as FORTH. If effort is -2 be spent on improving the ease of programing, it should be spent on 5 i~plif y ing argument prepar a t ion 2nd stack manipulation. Postfix rutation, with the applicative style of xograrrrning that it pduces, has so mny advantages that it should not be sacrificed to an algebraic notation that is rmt “natural,” but only some- thing we all learned in school.

THIS IS THE END! THE END @FVOLUME II #I! THE END OF YOUR MEMBERSHIP? DON’T LET IT HAPPEN! RENEW TODAY! CHECK THE LABEL FOR RENEWAL DATE! SEND A CHECK TO FIG TODAY! MAKE THIS YOUR BEGINNING! RENEW NOW!

a

MAKE A COPY FOR A FRIEND! POST COPY ON YOUR BULLETIN BOARD! FORTH UlrnEnSlOnS

FORTH INTEREST GROUP Volume II P.O. Box 1105 Number 2 San Carlos, CA 94070 Price S200

22 General Information

Publisher’s Column 1Lyons’ Den

23 Temporal Aspects of the FORTH Language

26 A Generalized Loop Construct for FORTH

29 File Naming System

32 Towers of Hanoi

Letters =,h shed by Forth Interest Group PUBLISHER’S COLUMN = L zaumeI1 NO 2 July/August 1980

Cdblisher RoyC Martens Summer IS here Lazy days should abound but not at FIG and FORTH DIMENSIONS Individuals Ecltorial Review Board and groups are working hara on Standards and Bill Ragsdale Cases Soon there will be announcements and Dave Boulton printing of these efforts In fact, if everything works Kim Harris out right, the next issue of FORTH DIMENSIONS John James will be the big one that everyone has been waiting George Maverick for (have you renewed your subscription and membership?) This doesn’t mean that we aren’t FORTH DIMENSIONS solicits editorial material, eager for more articles and letters from members, comments and letters No responsibility IS send them. More issues are in the works assumed for accurscy of material submitted ALL MATERIAL PUBLISHED BY THE FORTH INTER- Now that we have a few issues of the new looking EST GROUP IS IN THE PUBLIC DOMAIN. Infor- FORTH DIMENSIONS under our belt. we’d like to mation in FORTH DIMENSIONS may be repro- have your suggestions about improvements and duced with credit given to the author and the Forth additional information Do you want more tech- Interest Group nical material? More beginning input? More new product information? More77777 Let us know Subscription to FORTH DIMENSIONS IS free Remember your inputs are what make FORTH with membership in the Forth Interest Group at 31MENSIONS $12 00 per year ($15 00 overseas) For member- ship, change of address and/or to submit material, Have a nice summer Renew if you haven’t the address is already. Forth Interest Group Roy Martens P 0. Box 1105 San Carlos, CA 94070 LYONS’ DEN

=HISTORiCAi PERSPECTIVE = While listening to rhe tapes cf the FORTH Convention (available from Audio Village, P.O. Box 291, Bloomington, IA 47402, $16.00tor four FORTH was created by Mr. Charles H. Moore in tapes) I noticed puzzlement over how to com- 1969 at the National Radio Astronomy Observa- municate concisely the nature of FORTH, that rs, tory, Charlottesville. VA.. It was created out af what single term-operating system, compiler, dissatisfaction with available programming toois, interpreter-indentifies the class to which i! especially for observatory automation. belongs. How about referring 0.0 FORTH 2s a Meta Interpreter-a program for generating an inter- Mr. Moore and several associates formed preter (the application) !o provide an interactive FORTH, Inc. in 1973 for the purpose of licensing tool for solving applicatior, specific problems and support of tha FORTH Operating System and (sometimes referred to as JOL’s, job-orientea- Programming Language, and to supply applica- languages)? Other members ci!his class Ere LISP tion programming to meet customers’ uniqm and an obscure IBM system called PLAni, as well requirements. as APL. FORTH has unique features distinauish- The Forth Interest Group iscentered in Northern ing it from other members of this class, being more California, although our membership of 1100 is optimized for arithmetic than LISP, for example. world-wide. It was formed in 1978 by FORlH and being more compact and bower level than APL. programmars to encourage use of the language by Also, its implementatiix is more iike LISF thm the interchange of ideas through seminars and APL. publications. Continued on pQ. 3

Page 22 FORTH DIMENSIONS XI/? TEMPORAL ASPECTS OF THE return and nothing executes. But when FORTH LANGUAGE used later on this same word executes! As you learn mre, you discover that in A BEGINNER'S STUMBLING BJXCK order to perform some functions you must actually alter the traditional John M. Derick time sequence of programming and modify Linda A. Baker FQRTH's compiler after it already wrks P.O. Box 553 and is ebugged. Then, to add even mre muntain View, CA 94042 confusion, you find that some wrds, when added to the compiler, will execute different parts of that same Novice FofzTH programmers who have word at different times. Or, when you had previous experience with other, edit a Forrm program, save it on disk mre traditional, programing languages and then compile it; some parts compile almst invariably become mnfused when as expected but other words execute first dealing with FOKTH. A first time idiat ely. user sitting down at a FOKI'H terminal soon notices what seem to be time-based To an experienced FOKI'H programmer inconsistencies. That is, the language it is quite obvious that there are seem to require that things be done in actually three separate (but releated) the wrong order or that the language aspects of FOEFH represented in this itself does things Out of time order. example. To a beginner all of these The novice, striving to understand attributes are lumped together in

these supposed "inconsi.stencies" one tangled question of "who's on ~ detects time as a note of conarPnality first????" and "when did he get and therefore lumps them all together there????" as one oddity, while in actuality there are three separate areas of difficulty. With the exception of different parts of a word executing at different The interesting pint of this is times, these are very trivial problems that the cause of this confusion is so to an experienced FOKI'H programmer. To elementary that once the problems are the beginner they are totally new understood, it is difficult to look concepts that must be sorted out and back and pinpoint why the confusion grasped-even though once understood arose in the first place. This is why they really are trivial concepts. these elementary problem areas are not stressed in mst existing FORTH litera- kt us first address the mst basic ture and are just assumed to be part of of these three time related stumbling the longer than normal learning curve blocks; that of modifying the compiler. associated with EUU'H. Making it clear in the neophyte's mind that there are Before we mntinue it is important three separate, but related, factor to point out that there are several shortens this learning curve. steps (one may almst say laws) that always must be followed to generate Let us examine what situations cause object ccde fran source oode. Tradi- this confusion. tional programning languages take these steps in a straight line one-pass Sitting at a FORTH terminal, you manner. FOKIW also takes these same enter a FORTH word, hit a carriage steps (i.e., a compiler has been return and the word executes. Other written and installed). The difference times, though, you enter a line of with FOKIW haever, is that the act of FC"H words (including the One you just writing the canpiler is not intended to executed previously), hit carriage be a one-pass step. Instead it is a

I FORTH DIMENS IONS Page 23 recursive procedure where the mpiler "defining" words used in the compiler is constantly mdified and tailored to are actually tiny standalone compilers the users needs over and over again. in themselves and can bc u~edtr-) This alters the time sequence of things perform nini-compilations whenever they and is a slightly shocking concept but are referenced. the basic rules are still the same. Now that this compiler modificatiori In traditional languages a pro- aspect has been "factored" out of tnt- grammer goes through several temprally jumble of time related "Lmnfusions", separated steps to generate a user the beginner is still left with tno proqrarn: A compiler (or assembler), an second point of confusion: Nmely idiy editor, a link editor and loader are words sometimes execute imr-d;ate:y ,u;d all separately created and installed on sometimes do not. the user's system. Then the user edits a program, compiles it, links it, then The technical reason why Words loads and tests it. Everything is done execute immediately is that the in such absolutely clear cut steps that "precedence" bit associated with one is subtly led to believe that this that word is set on; but it is the is the absolute naturi? of the world. philosophical reasoning for the existence of the precedence bit that FOKX'H on the other hand is a highly is of importance to the neophyte. interactive, dictionary-based language where new additions to the language Again all of this is tied in with (i.e., user added words) are simply the fact that FOFU'H's compiler is an added to the end of the dictionary integral interactive part of the thereby "extending" it. FORTH's language. It is an integral part of compiler is part of this dictionary the language because it is mpsed of and therefore words added to the coTIIII13n FOHIH wrds used not only in the dictionary can actually affect or be compiler but in every other FORTH used in the canpiler. In FORM, this application as well. is not only possible, it is required if one is to fully use the power of the ktering a FofiTH wrd or words on language. a terminal, and hitting carriage return causes that wrd or mrds to be A simple concept? Yes. But it is imnediately executed and is similar to so contrary to traditional practice executing an already compiled and that it is hard for a neophyte to linked object mdule. The dictionary believe advanced documentation which is searching until the word is found tells how to build ccxopiler directives and the definition is executed. To do such as "creating" or "defining" words this, the word is preceded by a colon, while only alluding to the fact F'OFQH is put into the ccmpiler state, that the compiler can and should be and all words up until a semicolon will mdified. be compiled (i.e., placed into the dictionary for future sxecution!. This Therefore, let us emphasize this is similar to inputting source code to fact: The compiler in FORTH is not a F0HI;IIAN contpiler and getting object sacred. The traditional sequential & out. steps of writing a compiler and forever usinq that particular product do not The point being made here is that apply in FOm. Fom's ccmpiler may FORTH continuously changes between be modified at any time. All, or part "compiler" state and "execution" of it may be executed at any time. state. When in compiler state, As a matter of fact "creating" or -most input words are compiled, not

Page 24 FORTH DIMENSIONS IT/2 executed. Notice the word "most". Some words -are executed while in While it is beyond the scope of this compiler state. These are naturally paper to go into the usage of BUILDS called mpiler words. and DOES type words, it should be rxittd that they exist and really do have two These compiler words are identical separate times of execution. in appearance to any other FOKTH mrd. Indeed they actually are simply F"H The last point of confusion is: When words with the exception that their words contained in a "loaded" block precedence bit is set. They are execute immediately instead of com- analqous to assembly language pseudo piling (or visa versa). When FORTH ops or mpiler directives. A pseudo loads a block, it treats the incoming op (like ORG) in assembly language data alnost as if it were being read gives direction to or is "executed" by from a keyboard. Definitions are the assembler; not the object code. It compiled and put into the dictionary is never executed by the user program. as they are encountered in the data stream. But, if a word is encountered Thus, words in F0Kl'I-l may be "flqged" that is not contained inside of a to operate as pseudo ops. That is, definition (whether intentionally they may be chosen to execute inunedia- or not!) that word is executed imme- tely and thereby perform some act of diately, just as if it was entered fran compilation upon other words in the the keyboard. This is a quite straight definition; (even if they are imbedded forward, and quite understandable inside of a string of source code-- effect once it is pointed out. The just as a pseudo op would do in rule here is to put words to be assembly language). This "flag" is ccmpiled inside of definitions. Leave the precedence bit. When the FORTH words to be executed immediately interpreter detects that this bit is outside of definitions. set, it will cause it associated mrd to be executed immediately, even while A good example of word purposely in compiler rode. Usinq the word left outside of a definition is IMMEDIATE just after a definition is DECIMAL. This word is normally used as the method used to set the precedence the last word of a loaded block to bit. insure that after compilation the system is left in its standard base ten This is a very powerful feature state. of the FORTH language. It allows definitions to execute while in In scpm~lly, the temporal confusion compile mode and since FofiTH makes no that occurs when first usinq FORTH distinction between "suFplied" words is all quite elementary and under- and user written words the compiler standable--at least in principle. And itself can be added to and improved. at a beginners stage, principle is very This feature is called "extendabili ty". imprtant . There are certain defining words The three general categories; in KXU'H that take the trait of "when a modifying the compiler, compiler word is executed" one step further. directives using the precedence bit, Conceptionally advanced mrd such as and loading and cwnpilinq blocks, all BUILDS and DOES allow a definition to perform execution at predictable be constructed so that the first nalf times and really do have a direct of the word will be used at compile correspondence with traditional time but the semd half will exemte progransninq sequences. at exemtion time.

__ - - -. FORTH DIMENSIONS Page 25 A GENERALIZED LOOP CONSTRUCT FOR FORTH -

For some time, I have been building my own version of a FOKI'H-like languaqe words in each loop, includinq none. with direct rather than indirect The meaning of the words BEGIN , threaded code, runninq on the 8080. WHILE , UNTIL , and AGAIN is Last year I learned that my approach is exactly the same as currently under- almst identical to that of URTH; this stood; no new concepts need be learned. is not surprisinq since the design For newCOmers to the language (of which criterion of highest possible execution we all hope for, and in larqe numbers) speed was the saw. To this end, the the learninq task is easier because we inner interpreter has one level of have reduced the number of FORTH basic indirect ion removed (compared to words while at the same tine increasing FoKTH) and jumps (as for IF , EISE , the power of the language by permitting LOOP , WILE , LJNTIL , etc.) are more powerful combinations of these compiled to their 16 bit absolute words. This is surely a good direction value, rather than a 16 bit offset. since the human (prcqrammr) mind is All this by way of preface that unsurpassed at manipulating symbols, although my "home base" is isolated but not in remembering them. from the West Coast and my implementa- tion of the following mrds may not be The Words exactly FoETH mpatible, yet I feel that the concepts presented are new and The following definitions work in useful in the FORTH environment. my system. In FOKH, where ELSE and XIF require a ampiled offset rather The article 'FOR'IW-85 "CASE" STATE- than an absolute address, the words MENT' by Richard B. Main in FOWTH WHILE , COMPADDS , AGAIN , and DIMENSIONS, Volume 1, Number 5 UNTIL must be changed slightly. catalytic effect in the development of these ideas, specifically the technique of saving an unknown number of addresses on the stack and usinq : BEGIN HERE 0 : i*Mr;>./%:t : WHILE LIT XIF , llFUE 0 : IY9t ,;:--t zero as a marker for the last address. : UNTIL DROP LIT XIF , , : iNqkc;,\TL , ;FYP!?*4li : CCUPADDS BEISG DllP Ir r(ERt. 1, It r.\.>:F L - \'!. . It seemed to me that one area to apply : AGAIN LIT XELSi , COMPADUS , : INqt!ilATt this scheme with god effect is in the : UNTIL LIT XIF , (UMPADDS . : I99t: ii't BEGIN ... UNTIL and BEGIN ... WIIE ... REPEAT loop constructs which currently permit only one exit test. Haw They Work, Comp ile Time This sometimes forces awkward stack manipulations to "or" conditions when BXZN Pushes onto the stack the tm or mre conditions must be tested, address to which the loop any one of which is sufficient to should jump, followed by a terminate the loop. The proposed zero. The zero is used as a constructs solve this problem, require market by the COMPADDS no more lower level CODE words than word. already exist, and add to the elegance of the language by rmving the word WILE (if used) Compiles a mndi- REPEAT. tional jump to the temporary address of zero, and also The generalized loop is constructed pushes the address of the one of tm ways: temporary address to the

REGIN . .. kH1L.t ... WHILE ... WHILE ... UNTIL I) r BEGIN ... WHILE . .. WHILE ... WiILE ... AGAIN

Page 26 FORTH DIMENSIONS 11 / 2 stack. The temporary address, which can never be zero, will later be overwritten by COMPADDS with the address of the next word immediately after the loop structure: this is how WHILE effects a loop exit. The operation is self-evident. UNTIL (temporary) Allows correct cunpilation of the CfXPADIX Conclusion word's REGIN ... UNTIL structure. It will shortly Generalized loop words BEGIN , be replaced with the gen- WH1l.E , UNTIL , and AGAIN have eralized UNTIL . been proposed. Their use provides, as a subset, the well known actions COMPADIE Overwrites the address of all of BEGIN ... AGAIN , BEGIN ... previous WHILE wrds until UNTIL , and BEGIN ... WIILE ... the last BEGIN . Each REPEAT (with the word REPEAT address on the stack (there replaced by AGAIN ). When used in may be none) is overwritten this manner the new mrds impse no with the vale HERE+2. The mre run time overhead in time or zero placed on the stack by space than the words they replace. the last BEGIN terminates If the new wxds did nothing mre, the overwriting and leaves they would still be desirable the address of the first word because they "orthogonal i ze" the in the loop on the top of the unconditional loop termination wrd, stack. making it AGAIN regardless of the presence or absence of the WHILE AGAIN Compiles an unconditional wrd . jump, cunpletes all previous WHILE words, and then But, as an added benefit of the new oompiles the address of the words, mre pwerful constructs such unditional jump, pointing as BEGIN ... WHILE ... UNTIL or to the top of the loop. BEGIN ... WIIE ... WIIE ... AGAIN are possible. Thus multiple tests and IINTIL Identical to AGAIN , except exits fran a loop can be arranged in a conditional jump is com- the most natural order, without the piled, allowing a conditional need to "or" the results of the tests. loop exit. These multiple loop exits do not violate the principles of structured How Thev -9brk. Run Time programing since they all lead to a corrm3n point; in other words, the loop, They work the sane as the previously as a structure, has one entry and one blown BM;IN, WILE, UNTIL, and exit. AGAIN. Future &search Error Procedures After much thought about the impli- Error checks can easily be added to cations of the proposed words in these words. This is done as belaw: relation to the FORTH philosophy of prqramning, I mst say that of the two danges wrought by these wrds, viz.

FORTH DIMENS IONS Page 27 ;.-.i ,~t-tt~c?yon~lizationof the loop But it is possible! A very useful :-!-?ruct, and the ability to have by-product of the Error Procedures of -~.iriplis looi., exits, I believe that University at Ulrecht, Netherlands is >I t!x*iondization is by far the mst that they always leave at the top of ll\i~ltt~rlttcsult. In FORTH, while the the stack (during compile time) a ', ~'t-y.jet of proqramminq consists of flag indicatinq the 1dentit.y of the c,xtc.wlirq the laquaye by creating many innermost construct, different for iicw words useful in the application REPEAT ... and DO ... ; it is then a cnvi roruwnt, even so, I believe that simple matter to arrange WHILE to thr? initial basic mrds, especially the have different actions and to compile structured proqrammirq constructs such entirely different CODE mrds depending as IF ... ELSE ... ENDIF , BEGIN ... on this value. Of course, we wuld not WI'IL , and DO ... LxxlP should be as limit the number of WHILE words few and as general purpose as possible. between DO and UDP . LLOPmust be modified, as was described abve for In addition, they should be care- AGAIN , to permit this. fully names so as to convey their action to programmers new to FoE?l'H, but Bruce Komusin familiar with similar structures on Ontel Corp. other, "industry stadard" languages 250 Crossways Park Dr. such as ALGOL, ?ASCAL, and C. The woodbury, NY 11797 construct IF ... ELSE ... THEN is prin this respect; the mrd THEN confuses novices to FORTH since it usually implies selection, while in this case it is really a construct terminator. I assume that this is the New Product reason why the change from THEN to ENIF was specified in FORTH-79. QRliForth, fran Interactive Computer Similarly, BEGIN ... END is confusing Systems, is now available for the North since it does not imply repetition to Star cmputer. rOIU'H cOmblnes struc- the averaqe programmer. FORTH-79 tured programming, stack organizatlon, partially corrects this confusion with virtual mry, mpiler, assembler, BEGIN .. UNTIL , but I believe some and file system into an extensible word signifying repetition should macrolanguage. Organized as a dic- replace BEGIN , such as EPW ... tionary of words, FOFU'H allows defining LTNTIL , REPEAT .. . AGAIN , and REPEAT new words that extend the vocabulary to ... WHILE ... AGAIN . suit any application. Words are compiled on entry into code ready for As for DO ... LxxlP , this construct idiate test, and exemte ten times cries out for a convenient way to faster than Basic. FORTH supports prematurely exit the loop. LEAVE coding time-critical routines in seems weird - at Gdds with commonly assembler for the fascest response. accepted practice - since it has a OmniForth contains the interaccrve deferred effect, takinq place only at FOHTH mnpiler (*led an F1g-FOIUl-l) r the end of the loop. Rlthough I wn't assembler for the 8080 and 2-80, file remove it from the languaqe, I suggest system, and text editor. Chni-Forth an alternative: rn ... WIIE: ... Ixx)p requires 24K mmry and %rth Star WS, . At the execution of the optional and costs $49.95; an optional Intro- WHIU , if the stack is zero the loop duction to FuKlM manual is available is exitted. Not possible because for $15.00. Interactive Computer WHILE is already used for the REPEAT Systems, Inc., 6403 DiMarco Road, .. . WHILE ... AGAIN loop, you say? Tampa, FL 33614.

Page 28 FORTH DIMENSIONS II/2 FILE NAMING SYSTEM each. Each name string is actually stored as a fixed length 32 byte string Peter H. Helmrs with any extra characters being padded University of Rochester blanks. A non-valid file is flagged by a -1 value for the block pointer, not by a null of special string. This particular FOKI'H file nmning system is set up to use a disk based The following is a list of the directory to name files which are primary user oriented words in this vised of a series of disk blocks. file naming package: The system does not include any specific file formats, but instead is (""R")FIND-NME (INDX) used to translate a filename to a block number. This block number can be a FIND-NAME searches for the Sl'R in the traditional "load block", a directory directory and returns its directory block for a linked set of random data index if found, or a -1 if not blocks, or perhaps the initial block in found. Thus a user can test for a a multi-block text file. Routines are -1 to see if a filename exists. available to control a disk's bit map of allocated blocks so that already INIT-DIREKTORY utilized blocks are not overwritten. Additional routines allow creation of INIT-DIRECTORY is used to set all filename/block entries at either fixed block pointers to -1's so that no block locations or at randan locations, files will be oonsidered to be in or deletion of file entries, directory existence. listings, etc. INIT-BIT* The philosophy in writing this package was that file formats should INIT-BIT-MAP is used to set all be user definable although several bit map bits to O's, thus indicating standard uses are being brought up for that no disk blocks are being text files, and data arrays stored in Used. consecutive blocks. By using the wrds available, additional file formats can (BLK#) FREE-BU be easily added. FREE-BLK is used to reset a given The file naming system presently block's bit map bit, thus indicating uses three blocks at the end of each that it is not in use. disk. The first block contains two data arrays: a bit map of block usage on the disk, and a list of block- pointers for each defined filename. RESERVE-BLK is used to set a given The bitmap uses one bit per disk block block's bit map to indicate that it to define whether the block is used or is in use.. not; the bit is a "1" if the block is used. The block pointer array consists of 64 integers which point to the filename's starting block nunher. A FIND-FREE-BLK is used to find the value of -1 means that the filename is first free block encountered in the undefined. bit map. It returns a "free" block number if one can be found, or a -1 The second two blocks contain 64 if the disk is full. filename strings of up to 32 characters

FORTH DIMENSIONS II/2 Page 29

---=TOWERS OF HANOI --

by Peter Midnight

SCR U 14 Here are the listings of a graphic 0 ( TOWERS OF HANOI Copyr~jht,1979, Peter Midnight ) 1 : PRESENCE ( tower ring PRESENCE -> boolean ) representation of the ancient Towers 2 RING + C@ = ; of Hanoi puzzle which adjustable 3 : LINE ( tower LINE -> display-line-of-top is 4 4 SWAP N 0 DO DUP I PRESENCE O= ROT i SWAP LOOP DROP : for any CRT terminal with curser 5:l- 1-; 6 addressing. 7 : RAISE ( size tower RAISE ) 8 DUP POS SWAP LINE 1 SWAP DO 9 2UUP I BL DISPLAY 2DUP I 1- COLOR DISPLAY 10 -1 +LOOP 2DROP ; Recently, when I got fig FORTH 11 : LWER ( size tower LOWER ) 12 DUP POS SWAP LINE 1+ 2 DU runninq on my system under North Star 13 ZDUP I 1- BL DISPLAY ZDUP I COLOR DISPLAY DOS, I decided translate this 14 LOOP 2DROP ; to 1s --> program into FORTH as an exercise and as a comparison between FORTH and MSG U 15 PASCAL. In the process I noticed some

inefficiencies but chose to translate SCR 8 15 them more or less directly, for the 0 ( TOWERS OF HANOI Copyright, 1979, Peter Midnight ) 1 : MOVELEFT ( size source-tower destiny-tower MOVELEFT ) sake of comparison. 2 POS 1- SWAP POS 1- DO DUP R 1t 1 BL DISPLAY 3 DUP R 1 COLOR DISPLAY -1 +LOOP DROP ; 4 : MOVERIGHT ( size source-tower destiny-tower MOVERIGHT 5 WS 1+ SWAP POS 1t DO DUP R 1- 1 BL DISPLAY The UCSP PASCAL program is available 6 DUP R 1 COLOR DISPLAY LOOP DROP ; 7 : TRAVERSE ( size source-towel destiny-tower TRAVERSE 1 by requestinq the Jan/Feb 1980 News- 8 2DUP > IF MOVELEFT ELSE MOVERIGHT THEN ; letter from Homebrew Computer Club, 9 : MOVE ( size source-tower destiny-tower MOVE ) 10 ?TERMINAL IF 0 N 4 t GOTOXY ABORT THEN P.O. Box 626, Mountain View, CA 94042. 11 ROT ROT 2DUP WISE >R ZDUP R) ROT TRAVERSE 12 2DUP RING t 1- CI SWAP LOWER ; 13 --> 14 15 Forth Prosram- SCR W 12 SCR 8 16 0 : TnWFRS OF i:ANOi COpyK:ght, 1979, Peter Midnight O(TOWERS OF HANOI Copyright, 1979, Peter Midnight ) ( ) 1 ( T:an?lated for speed comparison ) FORTH DEFINITIONS DECIMAL 1: MULTlnOV size source destiny spare MULTIMOV 4 1 = 2 i ?:rst exrend Forth to incluZe a feu features of Pascal ) 2 PICK IF DROP MOVE ELSE 3 >R R> : *?SELF ( In definition, this is a recursive use of new >R SWAP 1- SWAP R> 4DUP SWAP MYSELF 4 4DUP DROP ROT 1+ ROT ROT MOVE 4 LPTEST PFA CrA , ; IMMEDIATE word ) 5 ; ' : COTOX? X Y GOTOXY ) 27 C8IT 61 EMIT ROT ROT SWAP MYSELF THEN 6 6 0 MAX 15 MIK 32 + EMIT 0 MA% 53 MIN 32 + EMIT ; 7: MAKETOWER ( tower MAKETOWER ) : i'i EARSCAEFN 12 EMIT ; 8 WS 4 N + 3 DO CUP I GOTOXY 124 EMIT ( LOOP DROP ; C : ZDRt2P DROP PROP ; I 9: MAKEBASE ( no arguments 1 9 : PICK SP? SWAP 2 + @ ; 4 + 6 3 + 4S ( ) ; ;L. : 4DUP 4 PICK 4 PICK 4 PICK 4 PICK ; 10 0 N GOTOXY N 0 DO EMIT - LOOP ,. 11 : I 1 !r CCP;STA:ITWAX ( rnaxlmum permisable number of rings ) MAKERING tower sire MKEHING 2DJP RING t 1- C! SWAP LOWER ; i? XXAX VARIABLE (N) : N (~iI ; ( formerly a constant ) 12 : SETUP ( no arguments ) CLEARSCREEN 13 0 CONSTANT HELL-FREEZES-OVER 43 CONSTANT COLOR ( t ) 13 N 1+ 0 DO 1 RING I i CI LOOP 3 0 DO I MAKETOWER LOOP 14 0 VARIABLE RING N 2 - ALLOT ( array Il..Ni Of bytes ) 14 15 --> 15 MKEBASE 0 N DO 0 I MKERING -1 *LOOP ; -->

SC'R I 13 SCR 8 17 0 ( TOWERS 1979, ) 0 ( TOWERS OF HANOI Copyright. 1979, Peter Midnight OF HANOI Copyright, Peter Midnight : ( 1 : DELAY ( centiseconds DELAY ) 1 TOWERS quantity TOWERS 2 0 DO 17 0 DO 127 127 DROP LOOP LOOP ; 2 1 MAX NMAX MIN (N) I REGiN 3 : POS ( location POS -> coordinate ) 3 SETUP N 2 0 1 4 4 0 7 SO 4 2N. 1+ Nt ; OVER POS N t GOTOXY N DO EMIT DELAY LOOP S ROT 4DUP MULTIMOV 5 : HALFDISPLAY ( color size HALFDISPLAY ) : 6 0 DO DUP EMIT LOOP DROP ; 6 HELL-FREEZES-OVER UNTIL 1 7 : ( line color size ) is 9 ZDUP HALFDISPLAY ROT 3 < IF BL ELSE 124 ( I 1 R 9 THEN EMIT HALFDISPLAY ; 9 ( 1: : JIsPLAY ( size pos line color DISPLAY ) 10 Results: DELAY runs much slower in Forth than in Pascal. 11 I: SWAP ?R ROT ROT OVER - R ( color sire pos-size iine ) But the rest of the program is over twice as fast in Forth1 12 GOTOXY R) ( color size line ) ROT ROT i 12 13 --> 13 Note that CLEARSCREEN and GOTOXY are terminal dependant. 16x64 or 14 14 NW should.be 10 for 12 for 24x80 screens. I 15 15 MSG 8 15

Thanks to "THE 1/0 PORT", the article on F0KIT-l by Art Sorski in their Official Newsletter of the Tulsa April 1980 issue. Address: The Tulsa Computer Society, for the feature Computer Society, P.O. Box 1133, Tulsa, OK 74101.

Page 32 FORTH DIMENSIONS II/2 __. LETTERS text file system with variable record length and blanks mmpaction. I feel that this system will make it easy to write programs in a more readable I'd like to t3ke this chance to format since this better formatted text acamplish several aims. First, let me will use less space than the current congratulate Roy Martens and the entire block oriented text editors. Thus editorial staff for a fine puclication there will be less of a temptation to in FORTH DIMENSICNS. use a short, cryptic coding style. My method of blanks compaction is to use ?ly interest in FORTH :s far from the MSB of each text character to flag passive; I have wen usir,y rhe 'kiver- a mmpaction count byte. When listing sity of Rochester's (mv Lenplcyer, by a program in the editor, the compacted the way) URTH dialect for several years blanks can be re-expanded while they nw. While at first I used it mainly can be interpreted as blanks (due to at home for a private music synthesizer changes in the WRD routine in vwnl) research project, I have mre recently when loading the text. Text will be been applying it with success to stored on disk blocks as an integral several laboratories within the number of lines of text per block with University's Medical Center. The each line being defined as 0 or mre applications have prima ri ly been characters followed by a carriage concerned with slow speed (10 to return character. 100 samples per second) analog data acquisition and analysis - the latter Text will be able to span multiple involving the use of the AMD 9511 IC random blocks to avoid any "artificial" for nurrber crunching (and it is fast program length constraints due to fixed ... !). These data acquisition systems block size. Blocks are associated have been described in an article which together via a doubly linked (forward I just recently submitted to BYTE for and backward) pointer scheme while publication (I hope). block usage is kept track of via a bit map (mre on this later) mrrespondinq While using FOKEI in these appli- to the disk's block utilization. So cations, I have developed a set of far the text editor has been written, goals for the elimination of some of but not fully debugged. However, the the limitations of FORTH (there are bit map and filing name system has been .sane, you know ...1. One of the major written and used for several mnths. problems has been saving only three I'd like to discuss them here as characters plus the length for identi- the type of entity which should be fiers; I have just recently implemented standardized for FIG FOEiTH usage. Let changes to adopt (in URTH) the FIG me try to motivate this building of standard. Using primarily S-100 file structures by analogy to building hardware, I am also ncw implementing a data structures in FoIiTH. hardward debug facility for FOKEI which all- easier program developnent. The IN FORTH (or at least URTH) one design is very simple, but allows traps can use some system features to define at instructions, memory references, any arbitrary data structure. One and/or 1/0 references. I consider this which I've used recently is: method of debugging immeasurably mre useful than just software trapping at : IPARAM eacb pass through NEXT. which might be used: Additional FORIM changes planned are the inplementation of a random block IPARAM MY-VIIUW&-INf'M;ER

FORTH DIMENSIONS II/2 Page 33 I The important things to notice in this file system so that it might this example are that the IPARAM data stimulate comments and improvements type first uses standard dictionary from the public domain. features to add new specific variables 1 - in this case MY-VIRTUAL-INTM;ER - to Thanks very much, and keep up the the dictionary. IP-I also sets aside good wxk.. .. some dictionary spa= - in this case I just one word - to store data for Peter H. Helmers MY-VIRTUAL-INTEGER. Thus there are tm University of Rochester important actior,s here - that of Rochester, N.Y. linking a variable's name into the I dictionary, and that of reserving dictionary space for a variable's storage requirements . 1 In December I got tired of waitinq The flle system that I have been and implemented FORTH-65 from the evolving also achieves tm analogous fiq-FOHIH &el. By the end of Decem- actions to those above. First, it has ber I had it up and running. This 1 a way of linking a file's name into a version follows the model exactly diskettes name directory, and second, except for printer mntrol, the disk it has a way of reserving disk block kinkaqe, and the inner interpreter. space for a file's sole use. Note, 1 that it does not concern itself in The jump indirect in the inner any manner with__~- how the file is interpreter doesn't always work, JMP logically formatted. As such, it is (SXXFF) doesn't work correctly on a L not a complete file management system, 6502. If a CFA ends in SFF it's I but only a comn protocol for various goodbye ~~. logical file structures! L This bus bit after my third re- Let me explore two uses of file assembly of FORTH-65. The inner types built on this foundation. The interpreter I'm now using is con- previously mentioned text file system siderably slawer (60 cycles) but it is L logically builds a file structure reliable. by the use of doubly linked random blocks. But in another case, the file I assembled FORTH-65 through the t is logically built up as an array disk 1/0 (SCR #69), Screens 72 through of consecutive integers in consecu- 92 reside on disk and are compiled tive disk blocks - thus linked only as needed. What I need now is the implicitly. Other logical structures ASSEMBIER vocabulary. Has anyone done L are as diverse as are FORTH data any work on a FOlU'H as&ler for the tyPes. 6502? L In summary, what I am proposing to 5CR I44 0 I RANDOM NCMBER CENERATOP E I be discussed and hopefully standardized 1 is a mrrmn structure which can used 2 DECIRAL be 1 1 to name files and reserve disk 4 0 VARIABLE SEED t space 5 for files. I am not suggesting any 6 : [RANI)) SEED S 259 3 12767 AND DUP SElI) ! ! 7 specific file structures or formats 8 : RANDOn [AANDI 12767 */ : InANGF -1 1 9 for standardization. I am enclosing a '0 is t 11 copy of the source listings and some 12 13 (hastily written) documentation for 14 15 L J.E. Rickenbacker Houston, TX L

Page 34 FORTH DIMENSIONS I I / 2 FORTH UlNlEISlClIS

FORTH INTEREST GROUP Volume II P.O. Box 1105 Number 3 San Carlos, CA 94070 Price $5.00

Historical Perspective

Publisher's Column

36-89 Case Contest

Dr. Charles E. Eaker Bob Giles Steve Munson Arie Kattenberg Karl Bochert/Dave Lion George Lyons Steve Brecher R. D. Perry Mike Brothers William H. Powell Dwight K. Etvey Major Robert A. Selzer William S. Emery Kenneth A. Wilson E. W. Fittery Wayne Will/Bill Busler David Kilbridge

90-91 Meeting Report

92 Meetings

93 Call for Papers

FORML Co, ,fcrence

Nat ionaI Convention Published by Forth Interest Group

Volume II No 3 September/October 1980 PUBLISHER'S COLUMN = Publisher Roy C Martens

Editorial Review Board Busy, busy, busy. That's what its been for the last 8111Ragsdale couple of months. Here are some of the things that have Dave Boulton been happening. Kim Harris John James Dave Kilbridge 1. We've reorganized the order processing for the George Maverick mail order items listed on the last page. The volume has increased so much this year that we had gotten FORTH DIMENSIONSsolicits editorial material, com- several months behind. Now, its all being handled ments and letters No responsibility is assumed for at one location and we even have a phone number accuracy of material submitted ALL MATERIAL PUB- for checking on your orders (41 5) 962-8653. If you LISHED BY THE FORTH INTEREST GROUP IS IN THE have technical questions DO NOT CALL, write to PUBLIC DOMAIN Information in FORTH DIMENSIONS the box number so that your request can be routed may be reproduced with credit given to the author and to the most helpful person the Forth Interest Group 2. We can now take VISA and Master Charge orders Subscription to FORTH DIMENSIONS IS free with by mail and by phone, (415) 962-8653 The charge membership in the Forth Interest Group at $12 00 per on your monthly statement will be listed as "Mt. year ($15 00 overseas) For membership, change of View Press". This was done because FIG isn't set address and/or to submit material, the address is: up to handle charges. We still aren't ready to handle Forth Interest Group purchase orders or delayed billings. PO Box 1105 3. The August issue of Byte magazine has put FORTH San Carlos, CA 94070 ON THE MAP. We are receiving 50-60 orders and requests for information a day. We have a supply of the issue and can furnish them to you (see the Mail Order form on the last page). 4. This Issue of FORTH DIMENSIONS has 60 pages and includes all the CASES that were submitted. Don't get your hopes up for more FD's this long. =HISTORICAL PERSPECTIVE = Next month we go back to our regular size. Congrat- ulations to all entrants! FORTH was created by Mr. Charles H. Moore in 5. Two events are coming up soon. The FORML Ad- 1969 at the National Radio Astronomy Observatory, vanced Conference will be held November 26-28, Charlottesville, VA. It was created out of dissatisfaction 1980 at Asilomar Conference Grounds, CA. The with available programming tools, especially for ob- National FORTH Interest Group Convention will be servatory automation. held on November 29, 1980 at San Mateo, CA. See Page 94 for more information and to register. Mr. Moore and several associates formed FORTH, Inc. in 1973 for the purpose of licensing and support Of the FORTH Operating System and Programming Lang uage, and to supply application programming to meet My thanks to the Judges and Editorial Review Board customers' unique requirements. for all the help they have given me on this BIG issue. Without their assistance, much of it done late at night, The forth Interest Group is centered in Northern you wouldn't be reading this issue for months to come. California; although our membership of 1100 is world- Many thanks! wide. It was formed in 1978 by FORTH programmers to enccurage use of the language by the interchange Of ideas through seminars and publications. Roy Martens

Page 35 FORTH DIMENSIW II/3 =CASE CONTEST CLOSES= The judging was based on a variety of factors:

This issue of FORTH DIMENSIONS is 1. the approach taken, including another special issue, chiefly devoted degree of generality: to FIG'S CASE Statement Contest. The contest, arinounced in FD I/5, Jan./Feb. 2. the success and efficiency of 1980, Drought entries from sixteen the implementation, e.c3., a mdividuals and teams, showing a high minimum of computation and level of interest and activity mng dictionary use should be left to the membership. execution time;

All the entries are FuDlished here. 3. MIR'IH-like style, Fncludinq good They shm imaginative thinking and hard documentation on the screens; wrk, and illustrate the many different ways that FORTH allows the user to 4. overall prose description, implement a single coxept. Although together with an evaluation of no one entry seemed to get it all the advantages and limitations together, many show some very good of the approach or implementa- work. tion;

Our panel of Judges did not settle 5. adequacy and clarity of exam- on a single winner, but instead have ples. decided that the prize will be shared ammg three entries. These are Dr. Hawever, the judging did not involve Charles E. Eaker, Steve Munson, and the loading and testing the entries on a team of Karl Bochert and Dave Lion. running FORTH system.

Each of these winners will receive a The judges felt that mst entrants $50 prize and a one year subscription were not getting close enough to what to Infoworld. The high interest in the is possible in FORTH. They seemed to contest has justified increasing the think dong narrow lines. A general overall prize from the $100 announced CASE implementation should be efficient (including $50 contributed by FORTH, both for the positional case (where the Inc.) to $150. Infoworld kindly values tested are restricted to the donated the subscriptions. first N integers, for example, similar to FDRTRA"s canputed ma), and for Eaker's entry is particularly well the general "keyed" case, where a organized, and has a clear, readable value, not necessarily an integer, is writeup. He implemented a keyed CASE tested against a sequence of explicit statement, and uses non-obvious words. values. Very few peaple tried to solve (See below for the difference between both. positional and keyed CASE statements.) This collection of contest entries Munson put so much thought into the make this issue of FD an excellent contest that he included several source for the comparative study of versions, differing in the type of data implementation techniques. Interested that keys the CASE statement, and in FORTH students should read each entry keyed versus positional ordering of to pick up helpful techniques and cases. evaluate style. (Caution: Any entry may also show poor techniques ard weak Bochert and Lion suhitted a mat style.) positional entry. It includes the ability to alter the binding of cases Forth Dimensions welcomes more to case bodies after compile time. contributors.

FDR" DIMEISIONS II/3 Page 36 :QN OOVER= IF mPIMMEDIAm JUST IN CASE ELSE 10 CNER = IF DROP DIRECT ELSE 20 CNER = Dr. Charles E. Eaker IF DROP INDEXED ELSE 30 WER = IF DROP E)(TENDED ELSE DROP MODE-EMR Even though FDRTH provides a variety ENDIF of program control structures, a CASE ENDIF structure typically has not been one of ENDIF them. There is no particular reason ENDIF RESET ; for this since, as we shall soon see, it is not difficult to implement c;EN is defined to expect a 16-bit one. number on top of the stack. For each IF, this number, the "select value," is There are two different approaches copied and tested against a constant, one can take to implementing a CASE the "case value." If the select value structure: vectored jumps and nested equals the case value the appropriate IF...ELSE...THEN structures. Vectored code is executed. If all tests fail, jumps provide the greatest speed at m-EWR is executed. Notice that run-time but produce enormous compiling GEN meticulously keeps the stack amnplications. So, takiny the path of clean. least resistance, here is a proposal for implementing a CASE structure 'for Depending on the select value, FDR"H which is really just a substitute sane action is performed on the apcode for nested IF structures. But, even and opera&, and (;EN remOves them fron though the proposal is logically the stack. Consequently, before each redundant, there are a number of test, CEN must copy (OVER) the select practical benefits which make it worthy value, and if the test is successful, of consideration. the select value must be dropped from the stack to expose the data values To help this discussion, consider a prior to the appropriate routine being word which might appear in an assembler called. vocabulary with a glossary entry as follows: But wouldn't you rather code this thing this way? GEN operand, me,mode selector -- :GEN CASE Used by the ASSEMBLER vocabulary ow mIATE EMX)F to generate opcodes. 'Mode selector' 10 OF DIRECT ENIBF is the value which indicates which 20oF INDEXED ENDOF addressing mode has been specified. 30 OF EXENJXD EUDOF 'Opcode' is the value placed on the MXIE-EIWIR stack by the preceding mAemonic, and mE RESET ; 'operand' is the value to be used as the argument of the owe. It is certainly easier to see what this routine is doing, so carvnents are not as necessary, and changes and repairs are far easier to do. Here are Here is one way of coding GEN. the required colon definitions of CASE, OF, m,and ENDCASE.

Page 37 EQm DIEIENSI- II/3 dumny null is mpiled into the address and its location is left on the stack so ENDCASE will knm where to stick the address once it is knm. But there is already an address on the stack lust under the one which ENDOF lust plshed. This address was left by OF and it points to an address that shoul(1 hold 3 branch address to the code which follows the code generated by LWF. So, ENDOF swaps the addresses ad calls ENDIF to resolve the address at the address left by OF. Finally, ENDOF leaves a four on the stack for syntax checking.

It so happens that with these ENDCASE makes sure it has been 2ef initions both versions of GEN preceded by either a CASE or ENDOF. :ampile the identical code into Otherwise an error message 1s issued :ne dictionary. Let's look at the and canpilation is aborted. Code for -xmpiling details. a DROP is canpiled into the dictionary, then all the unresolved forward CASE makes sure that it is in a branches left by each ENDOF are mlon definition. Then it saves the resolved. Since there may be any .:slue of CSP (which contains the number of them, including none, ENDCASE ?sition of the stack at the beginning checks the current stack position sf this case structure) and sets CSP against what it was when CASE was gal to the present position of the executed, and performs a fixup by stack. The new value of CSP will be calling ENDIF until the stack no longer ised later by ENDCASE to resolve contains addresses left by previous farward references. Finally, it throws ENDOF'S. Notice that all of these i four onto the stack which will be branches are resolved to pint to the sed for checking syntax. CASE com- code after the DROP generated by ?iles no code into the dictionary. ENDCASE. In the case of GEN this is RESET. OF first checks that it has been ?receded either by CASE or an ENDOF. It doesn't take long to notice :f the syntax is in order, then code that OF generates an enoms amunt of :s compiled into the dictionary to code (10 bytes). This is a classic duplicate the select value (OVER) example of a situation that cries cut md test its equality to the current for a machine language primitive. If a Zase value (=). Next, code for a run-time word could be defined, let's conditional branch is compiled into the call it (OF), then each OF would dictionary followed by code for DROP. generate just 4 bytes two to point to Notice that at run-time the DROP is (OF) and two for the branch address. executed only if the select value What (OF) would have to do is pull the equals the constant for this OF... EMXIF top stack item (the current case value) pair. and test it for equality with the new top stack item (the select value) If ENDOF first checks that an OF has the test for equality is true then the pne before. If so, then it ampiles next item on the stack the select an absolute branch to whatever code value is also popped and execution follows ENDCASE. However, the address mtinues after the (OF) If the test to branch to is not yet known, so a is false execution branches using the

FDR"H DLMENSIONS II/3 Page 38 branch value following the pointer to Used in a colon definition in the (OF), and the select value is left on form: CASE ...OF...ENDOF...ENKASE. the stack. Note that OF...ENDOF pairs may be repeated as necessary. COOC 132) A PUL C PUL TSX 1.x B SUB o,x A sac aaa a- IF XNS,INS ' BRANCV Cf4 .! I. BEX I 1: * JMP THEN BPA!ICH 2FA ? JXP At compile-time CASE saves the : OF 4 ??AIRS COMPILE (CFI HERE 3 I 5 : :!i!!ELlIr\?E current value of CSP and resets it to the current position of the stack. The M6800 code listed above is This information is used by ENDCASE to straightforward except that is uses resolve forward references left on the code in BRANCH and OBRANCH. (OF) stack by any ENDOF's which precede should wrk in any FIG 6800 installa- it. n is left for subsequent error tion provided BRANCH and OBRAKH have checking. not been altered ( it doesn' t matter where they are located). Non-6800 CASE has no run-time effects. users will have to roll their own, but the high-level OF should make it clear OF -- addr n (oanpiling) what has to be done. nl n2 --- nl (if no match) nl n2 --- (if there is a match) The disadvantages of this CASE proposal are that execution is not as Used in a colon definition in the fast as a vectored implementation, and form: CASE...OF ...ENDOF...ENDCASE. in sane versions of FORTH, ENDOF and Note that OF...ENDOF pairs may be ENDIF cannot be distinguished. These repeated as necessary. seem minor compared to the advantages - and there are several. At run-time, OF checks nl and n2 for equality. If equal, nl and n2 are First, a CASE statement may contain both dropped from the stack, and any number of OF...ENDOF pairs, and the execution continues to the next ENDOF. constants may be arranged in any order If not equal, only n2 is dropped, and whatever. Actually the constants need execution jumps to whatever follows the not be constants. Between an DKOF and next ENDOF. the next OF the programer may insert as much code as he or she likes in- At canpile-time, OF emplaces (OF) cluding code which will compute the and reserves space for an offset at value of the "constant." CASE state- addr. addr is used by ENXX to resolve ments may be nested; a CASE...ECJDCASE the offset. n is used for error pair may appear between an OF.. .Ep.Rx)F checking. pair. Furthermore, there need not be any code between CASE and ENDCASE, nor must there be code between OF and DlllOF addrl nl --- addr2 n2 (canpiling) ENIX)F. There must be code which pushes a 16-bit number to the stack prior to Used in a colon definition in the each OF. Finally, this proposal form: CASE...OF...ENDOF...ENDCASE. follows tk fig-FORTH style of handling Note that OF...ENDOF pairs may be control structures. repeated as necessary.

fig-FORTH GLC6SmY At run-time, EMxlF transfers control to the code following the next ENDCASE CASE --- addr n (compiling) provided there was a match at the last

Page 39 EDR!lM DIMENSIOS II/3 OF. If there was not a match at the Judges' Cments - last OF, ENmF is the location to which execution will branch. This is an excellent development and At compile-time ENDOF emplaces presentation of a key case statement BRANCH reserving a branch offset, with single integer keys. The follw- leaves the address addr2 and n2 for ing features make it immediately error checking. IXDF also resolves useful : the pending forward branch from OF by calculating the offset from addrl to 1. The reader can easily understand HERE and storing it at addrl. what the statement does and how to use it. There are only four ENDCASE addrl...addrn n --- (compiling) words to learn, their functions n __- (if no match) are imnediately clear fran the --- (if match was found) example presented and their msare not confused with each Used in a colon definition in the other. (The ENDOF - ENDIF form: CASE...OF...ENDOF...ENDCASE. similarity will go away when the Note that OF...ENDOF pairs may be FIG &el drops ENDIF in favor repeated as necessary. of the Standards Team decision to use THEN. ) At run-time, ENDCASE drops the select value if it does not equal any 2. One form of the statement can be case values. ENDCASE then serves as entered entirely in higher-level the destination of forward branches fiq-FORTH, and rup immediately from all previous €"'s. on any FIG system. An optional code word (for 6800) with At compile-time, ENDCASE compiles redefinition of one of the a DROP then computes forward branch four higher-level words saves offsets until all addresses left by run-time memory and time. previous ~F'shave been resolved. Either way, the hole statement Finally, the value of CSP saved by CASE fits easily on one screen, is restored. n is used for error including canpile-time checking. checking. 3. The narrative documentation is (OF) nl n2 --- nl (if IIO match) zxcellent. The glossary defi- nl n2 -- (if there is a match) nitions are detailed (appro- priate for this forum). For The run-time procedure canpiled by general distribution they could OF. See the description of the run- be condensed to user-only time behavior of OF. information. This entry presents one kind of case statement out of several that are desired. We hope that this canpetent Dr. Charles E. Ekker and straightforward work will serve as Department of Philosophy a model to future developnent. State Uliversity of New York &wego, NY 13126

COME TO FIG CONVENTION NOVEMBER 29

M#IH DIMENSICN II/3 Page 40 THE : CASE GLXIGSARY ENTRIES

Steve Plunmn BYTECASE

Keycase defining word, used in the Having grown up on an ancient form: version of FORTH Inc. micro FORTH, I can appreciate improvements ren- 2BYTECASE cccc keyo case key the case key, case (dgfault dered by f ig-FORTH's renames and . . . END-CASE. Defineg cccc as a redefinitions. I was particularly case+ caseword kich expects a 2-byte key impressed by the source equivalence of on the stack at run-tlme. If knt HERE NIMBER DROP which functions the same although in one case one is key equals keyo (a 2-byte keyj, dropping the address of the first caseO (a previously defined word) will if it matches key , non-numeric delimiter, and in the other execute; will execute, and so case one is droFpinq the mst signi- Jn. ficant half of a double precision The # efault case will execate if 1s number ! on no match; no default specified, Nxlp is assumed. Cases may be IMMEDIATE words, but no My one beef is why was : made IMMEDIATE? Surely nobody wants a canpile-time execution will occur header in the middle of a colon defi- within the case structure. The nition. By the way, as you probably structure must be terminated by already know, this tends to mask an END-CASE. (See END-CASE, BYTE- error in the definition of ; on the CASE). listing I have for the 6502 fig - FORTH. "here is no [COMPILE] before BYTECASE the [ which means compile mode is never terminated. In fact, I am not sure I Keycase defining word, used in the see the point of the E property in yodr form: glossary. All words ought to be BYTECASE cccc keyo case keyl designed, at great pains if necessary, so that they can be compiled. My case . . . key, case EN%-CASE. definition of CASE denies the E pro- Defihs cccc as a casgword which perty of :, and I would be rash to expects a 1-byte key (most signi- assume no one would ever want to ficant byte is ignored) on the mpile CASE. stack at run-time. If the key equals key (a 1-byte key), case Please find enclosed a listing, (a previo8sly defined word) wily documentation, glossary entries, and a execute; if it equals key , case, will execute, and bn. The diskette. The diskette also contains so the assembler used to generate the default case will execute on no code, as it may nonstandard If the match; if no default is specifid, be NOOP assumed. Cases may be fig-EVRTH does not run on your system is IMMEDIATE words, but canpiletiiw as it on mine, feel free to edit no does execution will occur within the case ideas into polished fig-FORTH (I my am structure. The structure must a novice figger) and re-list the b.- terminated by END-CASE. ICppJ -. screens; however I believe they will END-CASE, CASE). require no modification.

Page 41 KRTH DIMENSIW TT/3 CASE structure ldentical to that of WE, all inline within a colon defini- Case defining word, used in the tion. Used in the form: : cccc fonn: optional words ; . Ihe cases m.d run-time activity are exactly as CASE cccc caseO case . . . described for CASE. (See CASE, case (defaillt case) ENLCASE.END-CASE) . Defirks cccc as a caseword which expects a 1-byte key (most signi- DO-STRINGCASE PI c + ficant byte is ignored) on the stack at run-time. If the index is 0, Copy glossary entry for CO-2BkTE- case (a previously defined word) CASE, substituting STRINGCASE for will0 execute; if index is 1, case 2BWEASE everywhere. executes, and so on. NOOP case& must be inserted for unused values ENI)-CASE P of the index; index limit is 65, 535. No protection is made for Uliversal caseword delimiter. It out-of-range indices or stack has no run-time activity, but at underflow. CASE remains in compile cunpile-time it may fill in an "exit mode (by calling : ) until termi- address" ( inline caseword ) , and/or a Mted by ENDXASE. (See END-CASE). case count ( keycaseword ) , or termi- nate canpile de(CASE, inline CASE P, c + for CDDE definitions 1.

Compiles a reference to the run-time SIRINCICASE procedure of the same name, a two-byte "exit address", a onebyte Keycase defining word, used in the case count and case structure form: identical to that of 2BYTECASE, all inline within a colon definition. STRINGCASE cccc keyo case 0 Used in the form: : cccc optional key case . . . key casen (de- words DO-2BYTECASE keyo caseO fauit cad) END-CAh. Defines key case . . . key case (de- cccc as a caseword Mich expects a fakt cake) END-CASE ofiional byte-string beginning at HERE 1+ words ; . The keys, cases and with a count of them at HERE (mi- run-time activity are exactly as cally fetched by WRD) at run-tine. described for 2BYTECASE. (See If the string equals key (any BYTECASE, END-CASE) . byte-string of 1 to 255 cfiaragters) , caseO (a previously defined word) a3-BYTECASE P, c + will execute; if it equals key case executes, and so on. TkL Copy glossary entry above, substi- defaAit case will execute on no tuting BYTECASE for ZBYTECASE match; if no default is specified, everywhere. NOOP is assumed. Cases may be IMMEDIATE words, but K) cunpile-time I -E P, c + execution will occur within the case structure. The structure must be Canpiles a reference to the run-time terminated by END-CASE. (See procedure of the same name, a ENDCAsE). two-byte "exit address", and a case

DIMENSIONS II/3 Page 42 Explanation of Screens by IJumber can serve as a flag for this distinction, providing that the case 100-102: To enable the loading of a defining wrd executes outside of a screen, delete the lcftmxt paren- colon definition, and the infine thesis. For all screens above 108, form does not. Instead of using a 109 must be loaded. Some screens binary tree (nested IF tests) with a load others that they require, hence new flag variable required for each loading all screens will cause some branch , consider using a caseword to be loaded twice. If it is not inside END-CASE, itself, to dccun- desired to load all the examples, plish an n-way branch based on tkic edit DECIMAL ;S on the same line value of a single variable! of any screen in which the word (EXAMPLE) appears on a line by -105: CASE is the sm,plest form of itself. n-way branch. It canplles a string of consecutive codefield xldresscs -103: END-CASE is an example of a (CFA's) exactly like the para~~t??~ terminator (or a leader, or any field of a colon definition. Tlie : structure) that is common to all on line 3 creates the header and members of some group (in this sets canpile mde, END-CASE termi- instance , casewords). The structure nates compile mode. Whereas the can be identical for all members of CFA's in a colon definition execute the group only because it behaves sequentially, only one CFA will slightly differently to each of execute each time a CASE is called. them. ENPCASE accomplishes this by It expects an irdex on the run-trme following a binary tree. At each stack; if it is 0 the first CFA node a flag variable is tested and executes, if is 1 the second CFA code cmon to the branch taken is executes, and s) on. No protection executed. All members of the group is male for out-of-range indices. (each caseword) must set or reset Credit for the basic form of CASE the flag variables that must be goes to J. B. Weems, also of Hughes tested to complete the execution of Aircraft, Fullerton. all their compile-time code. 106-107: Each casemrd is presented E3ID-E must be expnded for each in three forms: a ;CODE defining new class of casewords that use it word, a defining word, as a camon compile-time termina- and an inline version. Tne inline tor. lhis is done by creating a new version is perhaps closest to flag variable that is 1 only for ordinary usage, the members of the new class. The defining casewords are machine affected casewords are then amended independent and easiest to modify, to set or reset this variable (at and the ;CODE defining caseworas compile-time) depending on their are, in all cases, the fastest. membership in the class, and the new This is because they take advantage variable is tested in ENDCASE. So of the available system winter W far, I have included only two (which is set by NEXT) in order to classes: the unique, indexed CASE, idex into the parameter field of and the keycasewords. Each is the case structure; whereas ths further sub-divided into defining inline casewords must mve IP kl*xd mrd and inline forms. Note that the case structure after usirq It to select a case. Note that the inline match. Ihe default may be a NOOP, a casewords are not defining wods, pop of the parameter stack, or even and so do not require an auxiliary a link to another caseword. The name for the case structure. default case is optional, if none is specified, ,CFA canpiles a reference The method of putting the CFA to be to NOOP, automatically. executed into W and jumping to the last half of NEXT (which fetches The structure of a keycasewxd is as the code address and puts it into follows : the program counter), is based on the word EXECUTE as a model. The COUNT KEYo CFAo C FA1 "NEXT 6 + JP1P" used here is source KEYdlefault truncation for space purposes. It ... KEY, CFA, CFA assumes that no insertions are made in the begiMing of NEXT (an inser- Where count is the number of cases tion in NEXT might be forgivable if (default excluded), and CFA is the short and forbidden to execute at CFA that will be execute8 if the run-time, or if turned on momen- run-time key matches KEYo. The count tarily by an EXEVAR). In such a is not supplied by the programmer; it case, the safe thing (and in any is determined automatically by ,KEYCASE case, the fast thing) to do is to by counting the number of cases till copy the code for the last half of END-CASE at compile-time. The HERE 0 NEXT (however it appears on your C, on line 13 reserves space for the machine), rather than jumping to count, and it is filled in by END-CASE. it. The 1+ after the BEGIN on line 14 is incrementing the case count on the -108: A curious hybrid of high-level stack. The compiled count will be inside a CODE definition. IX)-CASE picked up at run-time to becm a Do is really a macro that compiles code LDOP index. When the index runs to similar to that executed by the 0, it indicates that the list of inline version. Note that if the cases is exhausted, and the defualt stack is 0, and DO-CASE executes address is to be followed. one of the cases, execution will not return to 3TEST, but to the word Just mder this count, on the stack, calling 3TEST (that is, the HPUSH is a flag that indicates whether the JMP will not execute). There is no prcgramner has not supplied a default danger of name confusion because the case. It starts at 0 on line 13, may two DO-CASE'S are in separate be changed to 1 by line 4, and is vocabularies. tested on line 11.

109-110: A keycase is so called All of the keycasewords, as written, because it requires a key associated reserve only one byte for the count of with each @A in the case structure. the number of cases. Hence, one is A key of the same type must be limited to 255 cases per case structure supplied at run-time. If a matches (0 is not allowed, either). However, a key in the caseword, the associ- keys need not be consecutive or ordered ated CFA will be executed. Ulless a in any fashion, as are the indices for match is guaranteed, a default CFA CASE. Keys may be 1, 2, or n bytes is required which is executed on no depending on the kind of caseword; CFA's are 2 bytes.

PORTH DIMENSIONS II/3 Page 44 In addition, inline casewords that a reference to a ,KEY appropriate compile a 2-byte address in front of to a given keycaseword may be stored the count. This "exit address" there (by !KEY , for example). A mre points to the first byte beyond the elegant solution, beyond the scope of end of the case structure. This this document, would be to make ,XKEY address is put into IP so that exe- an EXEVAR , a variable whose value is cution may resume after a case has assumed to be a CFA, and which is executed. Case defining words do not executed rather than fetched. !1KEY , need this because IP already points !2KEY , etc., would then be osed to set correctly; W is used to scan the case the EXEVAR to ' ,lKEY CFA or ' ,2KEY structure. CFA.

The 1 = IF on lines 1 and 9 is NOWSAVE and RECOVER are needed testing for NULL (alias X). NULL because by the time END-CASE is encoun- cannot perform its usual function of tered, one has typically already resetting IN, incrementng BLK, and compiled the default case as a key terminating the loading of a screen. instead of a CFA. This is because it The reason is that ,CFA uses ' CFA , breaks the pattern of KEY CFA , KEY which is capable of compiling a refer- CFA. And in any case, in order to ence to even an IMMEDIATE word. This recognize END-CASE, we must advance the has the advantage that an IMMEDIATE input pointer beyond it, and it is word can be called as a case, but no convenient to restore it so that compile-time execution is permitted in END-CASE can execute and perform its the middle of a case structure. Lines compile-time activity. RECOVER is, 1 and 9 prfonn part of the definition then, a way to un-compile and un- of NUU if one is detected. Not that interpret what has been done. the test assumes 8080 byte order; on some machines, the test for NULL The endless loop of line 14 is would be 0100 = IF. If, on your terminated by the R> DROP on line 10 system, a block equals a screen, all when END-CASE is encountered. This the testing for NULL may be deleted. assumes that ,KEYCASE wiil always call ,CFA directly. ,KEYCASE is designed so that one or more keys, CFA's, default, or fND-CASE -111: Line 10: BYTEASE is a typical may be on any given line. A key need 8080 ;CODE defining word. "HEADER not even be on the same line as the !lKEY ,KEYCASE" is the compile-time associated CFA. Do not skip lines in activity, and the mcro RUN-BYTECASE the middle of a case definition. Keys compiles tne run-time code. The and CFA's must alternate, the exception run-time code fiust leave VJ pointing at is the default CFA which has no key. a case CFA or the default iFA, and then execute that CFA. ,XKEY on line 7, is a duiy which is called by ,KEYCASE where it reserves 2 Warning: if your ASSEMBLER does bytes which will be filled in at not specifically define SEGRJ as HERE canpile-time when a particular casewrd (non-IMMEDIATE) , tkri you will fall executes (lines 8 and 9 on screen 111, through the ASSEMBUS intG FOR?H ad for example). The CONSTANT ,XKEY-ADDR find : BEGIN HER2 ; L,MEL)IAI'E. %la defined on line 6 is set to point to version will not work in macros, the twu bytes reserved in ,KEYCASE so because you wapt to crxnpile a reference

Page 45 E7oRll DIMENSIOEPj X1/3 to BEGIN that will execute when the find it hard to edit anything else into mcro executes. a screen. Source numbers may be used as keys, but they will be treated as Note how simply each key is paired character strings; the run-time is also 41th the word to execute upon matching a byte string, it is not normally the key (32 TWO, for example). The placed on the stack even if it is a only punctuation needed is spaces (the number. number of spaces is not important). The run-time code has two loops. -112: It is interesting that STEST does The outer one is counting down the not behave exactly like 4TEST. They numkr of cases; the inner one has an are designed so that pressing the index equal to the byte-count of a key terminal key "0" selects ;S to be plus one (the count, itself, is cun- sxecuted. Because is pared). Saved on the stack is IP and high-level, it has an extra level on the address of the next key in the case the return stack; hence, the endless structure (computed from W plus the loop on line 13 does not exit, but byte-count plus 3) screen 111 returns to the terminal with "OK" . -119: One application of STRINCICASE is as a canpact language translator. The Calling the colon definition "R> R> string key is the input word, and the DROP DROP" from 112 would have the word executed by the associated CFA is same effect as calling the code ;S from the translation. Such an association 111. is faster than a colon definition equating the two, because IP is not 113: Note that the inline code is 6 saved on the return stack, or restored. instructions longer than the run-time code of the defining word. These 'Be cases of a strinqcase constitute instructions pick up the "exit address" a sort of vocabulary, but the structure which was given space at canpile time is more compact than an ordinary by the "HERE 0 , "on line 7, and dictionary because it lacks link filled in by END-CASE. fields, code fields, and terminators. zhe arithmetic that advances W fran one -114: Same idea as 111, but a twbyte case to the next is almost as fast as key is expected on the stack. The low following a dictionary link, and the byte is in L and high byte is in H. code for RUN-STRINGCASE compares Compare the "," on line 12 with the favorably with (FIND). It is hard to "C," of 111 line 8. imagine a FORTH - like language trans- lator that would be faster or more 115-117: Self-explanatory. ampact. -118: Stringcase uses variablelength -120: High-level version of 118. 'Ihe keys (up to 255 bytes). At run-time it two nested loop are still there as DO expects bytes beginning at HERE 1+ with Llxlps, the address of the next case is a count of them at HERE. It will match saved on the return stack between the this string against its keys, executing loops, and the two pointers to the tw the associated CFA if a match occurs. byte-strings are on the parameter "bere is m restriction that the bytes stack. must be printable ASCII, but you may 121-122 : Self-explanatory .

MRTH DIMENSIOtG II/3 Page 46 -123: The word called by the default Another possible kind of keycase case is exactly like 1"ERPRET except might be called BITCASE, where the key that is does not need to do a BL WORD is a mask, and the associated CFA because the string is already at HERE, executes if the mask AND'ed with the and it is not an endless loop (so that value or: the stack # 0. The flag it IEJTERPRET's only one word). variables and canpile-tire code would be identical with BYTECASE; the run- GENlAN is, then, a STRINGCASE that time code would simply do an AND will, first, attempt to translate a instead of an XOR, and a 0 = NOT word? but if it is not in its vocabu- instead of 0 = . The casewords lary, it will IN"EKP~Tit normally. presented here by no means exhaust The endless loop taken away from the possibilities. The structure INTERPRET is given to TRASLATE whlch is deliberately left open-ended ts is then substituted for INTERPRET in encourage user creativity. the definition of Lx)m (it could also be substituted in the definition of Note that BI'ITASE, BYTECASE, 2BYTC- WIT 1. CASE, and STRINGCASE all difEer in name-length to avoid confusion on If one now loads a screen with WIUTH-3 systems even when prefixed by TLOAD, it should compile nonnally, with D3- or RUN- . the addition that EIN, ZWEI, and DREI will be understood as re-names, and Keycases have the gxprty that they executed irranediately. In order to be a can be chained together through their true translating interpreter, the DOES> default addresses (the key can be part of STRINGCASEmust be extended to changed at this point, as well). This respect compile mode by testing STATE, makes possible complex, high-level and either compile the CFA or execute sturctures in which casewords feed the CFA , depending . other kinds of casewrds. This is a tree with n brances at each node (a Note that ;S calls itself as a pattern similar to human brain cells). case. This is not only a way to fird ;S, the interpreter would not stop at with two default CFA's one could either ;S or NULL (it would, of course, put keycasemrds into 2-link structures stop at an undefined). The reason is such as binary trees. Furthemre, any that there is not an extra level on the CFA, including the default case, can be return stack (namely, TRANSLATE) an EXEVAR (see explanation of screen between the equivalent of LaAD (TLOAD), log), allowing the structure of the and the equivalent of INTERPRET tree to change dynamically at run-tire. (DEFAULT). Hence, executing ;S from DEFAULT is sufficient. to end the execution of GERMAN, but not of TRANS- ;S Steve rlunson LATE (which will inevitably call GERMAN Iil~~l~sAircraft Canpany again). However, calling ;S as a case, Fbllerton, CA 92634 since it is a CODE definition, will end the execution of "3LATE, and return Judges' Comments - An interesting ap- eventually to the terminal with "OK". roach to error control, by making : But if one had used the IMMEDIATE a part of error control. If version of STRINGCASE, there would, a preceding ; is missing, due to mis- again, be an extra level on the return editing, : will be encountered in com- stack, and ;S would again fail. In pile mode. It executes but contains this case, ;S would have to call a word ?EXEC, which produces an error message whose definition is R> R> DROP DROP if compiling. A little confusing but (see explanation of screen 112). it works.

Page 47 E'OR" DIFWISI~II/3

- EYCASE 2 IF iu*i *I a :c qEFE ILAF ' EP.13IF ELiE :F 4EFE iJAF ELlE Il1l:ti.E

13 BYTECASE inou 14 31 ONE 30 ::. 34 Tun 33 THREE DEFALLT EFIC-C;':E

5 ?AIE PIiIl ONE TUO THFEE END-CAiE

FORTH DIMEIUSIW II/3 Page 48 0 ( IN-LINE FYTECACE UUP? I 111 Loan HEX 2 3 CODE DO-BVTECAiE IF H YO*; IF !+ L 1Oc' 4 H INX. PI !P MOV. XCHC-. FUN-EYTECASE S e PO-CYTEiACE

44.- 7

COME TO FIG CONVENTION NOVEMBER 29

Page 49 FWIM DIMENS1CX-S II/3 A PROPOSED CASE At run-time word (CASE) uses one STATEMENT FOR FORTH integer parameter from the data stack and leaves none. The given parameter Karl BochertAIave Lion specifies which one of many cases will be executed. A single case is defined as a set of FORTH words which General DescriDtion is preceded by the word CASE or E3D- CASE, and followed by the word ENDCASE The CASE statement suggested here is or ENDCASES. Within a single case, the done in high level code for the usual rules of pairing still apply to 6800 version of fig-FORTH. It may the words: JD, u)oP, IF, ELSE, THEN, have to have some minor changes in BEEIN, AGAIN, WHILE, REPEAT. That is, order to conform to the FORTH-79 they must be properly matched with each standard. The names of the words other. were chosen for descriptive value. Case 0 will be executed if the The word that initiates the set parameter is 0, case 1 if it is 1, of cases is: etc. The parameter will normally be in the range: 0 thru (I of cases)-1. Thus, the case function wrks like the CASE computed 03TO found in sane versions of BASIC, with the exception that this code is in-line. Following that are as many sets of: Advan taaes ENDCASE .* CASE is very compactly compiled, so the number of 16-bit wrds of overhead as needed to represent all the desired is 2 * (# of cases +1) + 3. This cases hich are to be executed. !the excludes the code within each of the first set is for case 0, and each cases, but includes the ;S which successive set is for the next highbr follows each case. 'l3e following use case number. After the last set canes of the CASE function, having 3 empty the terminating set: cases and an empty default case will ampile as 22 bytes of code:

.- ENDCASES CASE which indicates the default code to ENDCASE be executed if the case number is ENDCASE outside the legal limits. It also ENDCASE marks the end of all of the cases, ENDCASES and causes the look-up table to be compiled. Word (CASE) , which is the run-time word, is surrounded by Here, it should be pointed out that parentheses according to f ig-FORTH the CASE function is only used within a convention, indicating that it is definition, and the above sample is normally never typed in by the user. part of a definition.

F"lM DIMENSIOIS II/3 Page 50 More Advantages after a ;S . AFpropriate canments for pat&ing are included in the definition CASE statements have little overhead of (CASE) . run-time code. In the FIG model this version of (CASE) executes 41 FORTH The way to find out which typ of words, 37 of which are code words. FORTH machine you are using is: ?his may be shortened by leaving out the two protective features, thus :PlR; executing 25 words, 22 of which are : P2 P1 ; code words. The fastest method takes P2 P2 - . about 0.002 seconds to execute. FORGET P1

There is practically no limit upon The printout will be 0 for the 'came the number of cases that may be cart- from' type of FORTH machine, and 2 for piled. The table of pointers will the 'return to' type. contain an address for each case plus an address for the default case. Another thing to watch out for is that while inside a CASE statement you Two protective functions in word no longer have access to any loop ( CASE ) w i 11 hand 1e neg ati ve numbers comter ( I ) which was created outside and numbers that are too high. For the CASE statement. During execution negative numbers, the equivalent of the chosen case there is one extra positive case is executed. For address on the return stack, covering numbers too high, a default case is up what was there. executed. It should also be noted that any intermediate case that will Conmile3 Structure never be executed still needs an ENDCASE, but the compiled code will Note: Each line shows the contents of contain only a ;S . The default one 16-bit word of nrrnory except case may be left out, and will then for the lines within braces: mpile like an empty case. , which signify any amount of memory, including none, which my One additional feature to point contain FORTH instructions.

out is that CASE statements may be (CASE) I the poinrcr to Code field address of (CASE) nested much the same way 'Do' loops pointer to end ,------as [ , J <<------*7 can. I. I I I :S I I [ 8 1 (( ------,I I 1. I II I , This PJCC ': J ( case * 2 1 <<------,III1 I contains Disadvantaaes I* 1 Ill I -the code is Ill 1 tor the ... . etc. : : : Ill I C*S.S ( case # n ! <<------,111 I There is one machine dependent I. 1 IIII.. I IS IIII I factor that must be considered before (defJUlt code) <<-----, I I I 1 I installing these words. Since we fool IIIII I around with return addresses in the return stack, we must know whether the return stack of the machine stacks 'return to' addresses or 'came from' addresses. The former is the situation where the address is not increment& * Any case code may be left out. The before doing the firstTetch after a resultant case segment will have ;S . The latter type of machine (my only a ;S in it. 6800 version) does do a pre-increment

Page 51 E'ORTtl DI)rlENGICBS II/3 The Result is:

hefinitions for 6800 Fig-FOWM TEST-WORD ( typed byhuman) -4 default case -3 default case -2 This is the case # 2 code SCASLI ( the run-tlme functlon I -1 ABS ( 8 make sure par~eteris + I R> ( qet addrera of pointer to table I 0 This is the case # 0 code lt 1 delete thlr line for 'return to' machines <------I 0 DUP ( get pointer to table > 1 2+ add this linr for 'return to' sachiner <------I ,R ( save final return Addreas 2 This is the case # 2 code SWAP 1. DUP ( find addresser into table of the .... I 3 default case OVCR SYAP ( 8 hlqhest legal case, . . .. I ( and the derircd case , . . . I 4 default case SYAP @ @ then choose the .... ) rux ( I best one I OK 4 ( read table entry for cnosen :as* 1 2- ( delete this line for 'return to' macainer <------\ ,R ; ( stack It b 'return' to it I Time Trials: *OTC: the lines marked '8' may be deleted to speed up eiecutlon I while sxrifrcrng protection. I Here we find out how long it takes to get to the proper case. The CPU I compile :he run-tine executor I I inlt cable pointer b get its rddr 1 clock is set at 1.000 MHz. The word I 8tJCk a marker on data stack I ; IWCDIATC (CASE) was defined leaving out the protection features. Then the follow- UDCASC CONPILC ;5 ( end of a case I ing definitions for timing loops are lLllL I stack a pcr. to next case I I INMCDIATE tried, executing null cases which do nothing. 100,000 loops are timed: CmMCS this word writer the look-up cable I DCC IllAL CaIPILt :s ( end of default caae ) : INNER l?OO 0 00 1 CASE ENDCASE ENFAZE ENDCASE ENDCXSES LOOP ; I put pointer for default case Into table I : SPECO . X. 100 0 W INNER LOGP . X : ncu >a ( teaporsrily save addr of pntr to crse[nl I SPECO Xx OC ( this was 210 seconds on the 6800 PORTH 1 WP ( look for cssef01 1 I? I dldn't find marker. ao: I OCGXN 1000,000 loops are timed, leaving cut , DUP 0- ( stare pntrs to case1111 chcu csselll I CNO ( until reaching the mutter b the CASE Dortion: TBEN : INNER2 lO?O 0 W mop : DROP I drop the marker I : SPCCJ 2 . X. ;30 0 ;a mm me :X. : OUP I dup the pfa I SPPDI XX Ox I chis uas 13 seconds on -& 6800 FVfrni 1 2. , I store pncr to camel01 I ( data stack is down to 1 itea: the pCs I Thus, it can be seen that it takes HERC SYA? 1 ( s:ore chis addr into pfa I R> I fetch addr of ptr to hiqhest nocoal case I about 2 milliseconds to vector to 2-. i IMEDIATE the desired case if the two protection features are left out. Putting in the protection would increase the time to about 3.5 n6ec. Karl Bocfiert Dave Lion Los Altos, CA 94022 A Test of the 'CASE' Function: Judges' Canrnents - fLst-you)..-- Karl and Dave were the only entry 5 -4 ( Cry a rJnqe Of PlClmOterS, .Oil* Of which .I* fllq.1 I 3) to make provision for pre-incrementirq I DU? . ( preceed each Ilne rlth the case 0 boinq triod I ClJL and post-incrementing versions of * This 1s the Case 4 0 code. CNDCASE WXT. This I ---case 01 does nothinq--- I ENDCASE refers to when the inter- .' ?his 1s th. yo8 I code' ENDCASE pretive pointer is advanced within * default ease IP ~cr NEXT. They give a test to check your CJ I do the next case on s new line ) mPt system. This version uses a canpiled table of indexes to give minimum execution time. The style and docu- mentation is to be complimented.

FQRTH DLMENSICRS II/3 Page 52 CASE AND PROD CONSTRUCTS : ?CASE ( nl n2 -> . Canpile- Steve Brecher time check for nl=n2. If fail

I syntax: ww CASEOE issue syntax error) ww CASE www ESAC [ 0 OK more ChSE/ESAC pdlKS <> IF CASSYNTX ERROR aIlowed, dC l(ASC 2 pSlCS for semantic sens0.1 ENDIF ; rn CASE www ESAC OTRERUISE ww [ OTHtRYISE OptlOnall ENDCASKOF : CASE ( 4 -> addr 5 . Executes ?CASE VJWW stands for O+ Forth words, syntax check: possibly including complete case campiles CASEBRANCH expression[s] , these possibly still with a zero offset; further nested. But code represented pushes address of by ww can make no net change to the offset so ESAC can return stack, as the case selector fix it later; pushes value is stored there. Runtime: 5 syntax check CASEOF pops, saves top of canpute stack signal. ) as selector. CASE pops, tests top of 4 ?c.GE I S,?tcr check1 stack vs. selector: if =, executes COM PI L E C AS E B RA NC H words up to next ESAC followed by words XERE 1 PUin addreas 0: offset so :SAC id7 par25 i:i after ENDCASEOF. If <>, executes words 0 , I ESAC will cr.arpe '.he 0 to +offser fat ;iSEaRAtiC31 after next SAC. CTTHERWISE is optional 5 ( ror LSA; syntax cneckl ; for readability. SELEC'IOR used any- where be tween CASEOF and ENDCASEOF leaves the selector value, provided no net change has been made to the return : ESAC ( addrl 5 -> addr2 stack since CASEOF; SELECTOR is an 4 . Pronounced alias for 'R'.) "eesack" ; "case" spelled backward. 31 CONSTANT CASSYNTX (Error Executes ?CASE number, case construct syntax check; fixes syntax ) the offset at addrl so the CASEBRANCH : CASEOF there will branch to the code after SAC: I -> 0 4 . Pronounced 'case of', iftee Parccl.; CCMPILE >R ( LO JaVO relector f3: CeStlng by CASES1 canpiles BRANCH with 0 I 0nd-Of-d.tJ 11gr.d: to CNCCASEOFI 4 I POK CASE JyntdX ckeckl ; a 0 offset, pushes the address of the 0 DWDIATE offset so ENCCASKIF can fix it later: CODE CASEBRANCH ( n -> . Forth branch leaves 4 for syntax to the offset check by later following inline if word.) n <> @RP, else bump IP over offset. 5 KASL I lyntar chock1 2 I CWC rill b. zheckinq for this1 Compiled by CASE. ) IcOMPrral CUE ( XLSE fixes CASE offset. ?usher ..'or of 0 offlet 1: compiles 'with BPA:KIIl S )+ RP (1 CMP, 2+ I ( CLSL leave1 2, C~SC,'OTBERWISf/ENGCAS~O~want 41

nt xr, I I: n <> (RP, I I? (I IP ADD. ( add inline oftset to IPI UMEDIATE NEXT, ENDIF, ( and .bcaneh~l IP I+ 292, ( else bap IP over in1ir.e oftietl YCXT, C: I and c?ncinue there.)

Page 53 FORTH DIMENSIONS II/3 : UI'HEFWISE ( 4 -> 4 . For readability, optionally written Steve Brecher after last ESAC to Software Supply identify code which Lmg Beach, CA is executed if no cases match. Judges' Canments - Performs compi 1e- This entry supports essentially the time checks. ) same syntax and semantics as the XCMP FORTH-85 CASE statement ( see FD I/5 ) , 4 ?CASE but offers the following advantages: 4 I IMMEDIATE 1. Compile-time syntax checking. 2. Drplicit (Yl'HEEWISE clause. : ENDCASEOF ( 0 addrl addr2 ... 3. Case selector is kept on return addrn 4 -> . stack instead of in a special addrx is the addr of variable. This allows nesting of an inline offset CASE constructs. following a BRANCH 4. 16-bit branch offsets are used, compiled by an ESAC. rather than a mixture of 16-bit Executes ?CASE addresses and 8-bi t offsets. syntax check; 0 on This eliminates the need for a the stack is an special run-time ENECASE word and end-of-data signal simplifies compilation. which was pushed by CASEOF; For each CASE.. .ESAC, patches the offset at addm so that the BRANCH NEW PRODUCT compiled by ESAC will branch to the R>DROP which END- 2-80 CASEOF compiles.) 4 ?CASE ( Syntax check) We have a Z-80 implementation of BEGIN -DUD unxLE I there's a nonzero offset on stack) FIG-FORTH that was derived directly from 2 ( CNDIP rill be checking for this) [CWPILE I ENDI? i ENDI? will compute, emplace offset) 8080 FIG-FORTH 1.1 and will run under REPEAT either CP/M or Cromemco CWS. The code C3(PILE R>DROP : ( code drapr caw .value from R stack) is optomized to exploit the additional IMMEDIATE 2-80 registers and instructions. Although this was developed for our own ALIAS SELEcl'CR R internal use we are willing to make it available at cost to interested FIG I PRODS/PROD/DCRP/CA~~L/KNDPRODS are aaslOqOuS LO CMCO?/CASC/CSAC/OT8E~WIS~/LZIDCAS~D?except there members. For $25.00 to cover media, is no selector valger aach PROD tests €or tf on stack.) copying, and shipping, we will send two 13 CONSTAUT PROSmTX 1 Error number, production set syntax) soft- sectored single density eight inch I PRODS ( -> 0 6 . Compile-ti- setup €Or PROD Set.) diskettes containing executable Z-80 0 1 end-of-data riqnal to ENDPRODSI 6 I ( ?Or PROD syntax check) FORTH interpreter, all source files, and IMCDIATK sample FORTH programs. Payment may be

I ?PROD I nl n2 -> . I sent by check or money order to the <> I? SROSXWTX PRROR PHDIZ : address below. Please allow us 30 days I PROD I 6 -> ddr 7 1 for shipment. LABORATORY MICROSYSTEMS, 6 ?PROD 61 4147 Beethoven Street, Los Angeles, CA 90066, (213) 390-9292. ( 0 ddrl &ddrZ ... addrn 6 -> ) 6 ?PROD I Syntax check.) BEXU -0OP WHILE 1 there's a nonzero offset of stack) 1 ( CUDW rill ba checkinq for this) [COMPILE1 ENDI? I ENDI? rill compute, emplace offmet) RZPI!AT I EYX'Ill DIMlEUSIONS II/3 Page 54 Execution A CASE STATEMENT Upon entry, a number correspording to the case is assumed to be on the !like Brothers stack. ''$CASE" then places ADDRl on the return stack. ExpressionAl is then executed, and 'I$=:" compares the value Approximately a year ago I was on the tos (top of stack) with the nos writing a program and needed a more (next on stack), which should be the powe r f u 1 branching construction than entry value. If these are equal, the the standard IF..ELSE..ENDIF con- entry value is dropped and ExpressionA2 struction. Somehow I decided on is executed before I*$;;" sets the qlementing Pascal's CASE statement in interpreter pointer to ADDRl (which is FORTH, and this is the one which is on the return stack). If the two described here. lhis CASE statement is values are not equal, "$=:* sets also included in the standard SL5 the IP to addrB and execution continues package, available from the Stackworks. until a valid case is found or the cases are exhausted, which causes ADDRl Some of the advantages of SL5's to be removed from the return stack and CASE statement are : the entry value dropped.

1) Infinite nesting is possible. The word ''NOCASE" always causes the $=: to execute the following 2) The CODE is machine independent. expression, simply by setting the tos equal to the entry value. 3) Programs are easier to read because of its simplicity. Examples of CASE statement usage CASE statement definitions : $WE Lm NU >I, I> 2 Q ,I : LXM!LEI BEGIN s- OILI - IT mop I> 1 . CBOICE? ' GCU Cyt us1 I> c )I 41 -: .. APPLE i ;; ( A LS f;r APPLE I mu ; 42 o: .. BLIlEBERRY - 1 :; ( 9 LS :or BLULIESRh I : S.' I> DIOI : MOUSE ow, 43 -: :cscan: 1 :: ; C IS for CHCRRY J : \ XASi 0, [ 15 Lor DATE 1 ciit IPI , 44 0: .. DATE 1 ;: D : 0: \ $-: IPL 0 45 0: PLJERBEIRY 1 :: ( E IS ioc ELDCSSERPY I : ;; \ s;; lLlr iAi I .. . : ww \ I> \ DIW inc suu 1 I Compilation During canpilation, "CASE" compiles the address of "$CASE" and a 0 for the address field. Every subsquent "=:" causes "$=:I' to be canpiled along with a dummy address field (to be set by CASE statement exanple the next ";; 'I ) . The word 'I; ;I' then cunpiles "$;;" and replaces the address The example shown above illustrates field of the previous "=:" with addm. the CASE statement's simplicity and when "CASEND" is finally processed, the pakler When EXFMPLEl is executed, a samething resembling figure 2 should be character is read from the keyboard. present. If the character is an "A", the string -- is displayed. the character I 9WI I I rnI1 I "APPLE" If ------_-- is a "B", the string "BLUEBERRY" &rA: L.praaaloa&l I- s-: 1 I --addrl I *Ipr.saioa&Z I-- 1;; 1 is shown. If none of the five are -- - selected, the string "WRONG" is -1: Lpraaaioul I --9-: I I addrC I *spr*aaioml2 I- 9;; I

-- I_ addrl: wr*aaronll-- I-- 9-: I I ddr2 I expr*a.ionl2 I- $;; I -2: I- I, I I ---mw I *XI:

Page 55 FORTH DIMESICBE II/3 NEW PRODUCT displayed and the loop is executed again until a valid (A-E) choice is FORTH FOR CP/M entered.

The COND Statement Mitchell E. Timin Engineering Co. has an enhanced version of FIG FORTH One particular advantage of the ready for immediate delivery. It is case statement is that an additional supplied on an 8 in. single density branching structure which executed diskette, ready to run on any system an expression based on a boolean with CP/M and at least 24K of memory. A expression can be defined with a few FORTH style editor with 20 commands is more words. I call this structure the included, as well as a virtual memory COND statement, and the extra words sub-system for software which is needed are shown in figure 3. The permanently stored on diskettes, then structure is much like that of the CASE loaded when needed. The user may also statement, as shown in the example in make permanent additions to the resident figure 4. FORTH vocabulary. A Z-80/8080 assembler is also included, allowing the user to : COND cm?rie CASE ; IUNBDIATE : CONDCND \ R> \ 2DROP HER5 SHA? : : IUnCDIATE create new FORTH definitions which : f:: IT R> a + >R compile directly into machine code. All ELSE R> I )R EHDIF i 2-80 or 8080 instructions may be used. : :: \ 5:: HERE 0 , : IMEDIATE The IF...ELSE ..., BEGIN ...UNTILL, and Flqur. 4. COND stacemelt definitions BEGIN.. .WHILE.. .control structures may be included in assembler definitions; these will automatically compile into : EXAMPLEI CON0 DUP o> :: r- PasxrIvE- I: appropriate machine code. DUP 0- :I T' ZERO' I: 1 :: T. NCGATIM' i: CONDCND i Other enhancements include an llqure 5. Era0pl.S Of COND StJtemnt uSJg* interleaved disk format that minimizes the time required for disk access. A The COND ExamDle 1024 byte disk block may be read or written in as little as 1/6 second. The Example shown above illustrates Eight of these blocks are maintained in the similarity between the COND con- RAM for immediate access and struction and the CASE statement. Vpon automatically swapped with others on the entry to EXAMPLE2, an integer 1s disk as they are needed. assumed to be on the stack. One of the strings "POSITIVE" , "ZERO", or The price is $75 for the 8 in. "NEGATIVE" is displayed depending on single density version, $90 for other the integer. diskette formats. Adequate documentation is included, suitable for Mike Brothers the beginner as well as the experienced The Stackworks computer user. Bloomington, IN 47401 FIG FORTH was originally defined by Judges' Cments - This is a practi- the FORTH INTEREST GROUP and is very cal method but not as portable as it close to the FORTH-79 international might appear. The 2+ in $CASE and $=: standard. will have to be relocated for preincre- menting 6800 systems. The COND state- Mitchel E. Timin Engineering Co., ment is a nice variation on CASE. 9575 Genesse Avenue, Suite E-2, San Diego, CA 92121.

MRTH DIMENSIONS II/3 Page 56 WHAT EACH DEFINITION FOR DO-CASE =DO-CASE STATEMENT = DOES:

DO-CASE consumes the case key value to [)wight K. Elvey be used later by the individual cases. This is the initialization statement for a DO-CASE field.

CASE does a canparison of the case key OVERVIEW OF STATEMENT: value and a case value. If a match is found the statements This is a DO-CASE written in FIG between CASE and the next ENDCASE FORTH. It allows the operations of are done, then operation is picked statements on the condition of a match up after the END-DOXASE staternent; of a case value and a case key. This else operation continues after DO-CASE also has a range case that the END-CASE statement and continues allows the use of the condition t~ be until END-DO-CASE or the next done on a range of case key values. successful case. 'Ihe MT CASE and the NULL CASE concept are also allowed in this DO-CASE. RANGE-CASE does a comparison of the case key value and an inclusive range of values set by the tho case values. ?he first case value on the stack must be greater in value then the next case value on the stack. SCR 8 19 o m-crse ALSO COMPILE < ...3 LIKE CMPILE 1 The operation of RANGE-CASE is 1l)l 2 : COMPILE< ?COOP BSGIN R> DUP 2* >R @ DUD ' 3CPA - IF DROP otherwise the same as CASE. 3 1 CUE , 0 CNDXF UNTIL : 4 5 : DO-ZASL CQlPILL )R 0 S : IMMEDIATL 6 : CASE I ?PAIRS COMPILE( P OBRANCR) HERE 0 , 7 i IMMEDIAtE END-CASE irrdicates that the conditional 7 I IAHCE-CASE 5 7PAIBS COMPILE[S SWAP - O< 0- OSRANCS) HERE 0 , CASE or RANGE-CASE is ended. It 8 CCUPILECR - O< OBRAMCB> RERC 0 , HERE CGXPILL BRAHCR !!ERE 0 , 9 HERE SWAP >R RGT >R R - R> I OVER - SWAP I R> 7 ; IMEDIATE must be paired with any use of CASE 10 : END-CASE 7 ?PAIRS COMPILE 8UNCR 3ERE 0 , SWh? BERE OnR - 11 SWAP I SWAP i* 5 ; IHMEDIATS or RANGEXASE. 12 I RID-W-CASC 3 ?PAIRS -CUP IF 0 RERE OMR - SWAP I LOOP 13 ENDIP CQlPILECR) DBOPJ ; I?(MEDIATE ;S 14 15 END-DO-CASE is used to close a DO-CASE * field. Its main purpose is to do the cleaning of the stack and provide an exit point for the CASE SCR # 29 statements. DO-CASE must be paired 0 ( ULAllPLE or Do CASE ) 1 t eUrrpLf DO-CASE With a closing END-DO-CASE. 14CASE . TEE NUMBER WAS 4 CR CND-CASY 3 5 3 RMGf-CWE .. THE NUMBfR IS 3 OR 5 CR CIID-CASE 4 6 CASE . WE NUMBER 1s 6 CR LND-CASL S I NULL OR NOT CASE 1 . TRE NUMBER ISN'T 3.4.5 OR 6 . El c;LossARY ENTRIES 6 EID-CASES ; ;S 7 8 9 CASE 10 11 11 n -- (run-time) 13 I4 n -- addr n (mpile) 1s Used in a colon-definition in the form:

n(ll W-CASE ... n(2l CASE (tp) ... EWJ-CASP (fp) ... END-IXI-CASE COME TO FIG CONVENTION NOVEMBER 29

Page 57 EW" DIMENSIOS II/3 (n3 = nl + 1) and an offset at At run-time a comparison of n(1) and address (addr2) to be used later. n(2) is done. If there is a match the true part is executed, then execution resumes after END-DO- CASE. If there is no match execu- tion continues at the false part -- (run-time) addr(1) addr(2) ... 3ddrial) nl n: (fp). It must be followed by an --- ( i 1 END-CASE and an END-DO-CASE. It comp c 1 must be preceded by a DO-CASE. At run-time this terminates a At compile-time CASE compiles a DO-CASE field. See D;)43SE or CASE branch and reserves space for an for its use. offset at addr. addr and n are used by END-E to resolve the offset At compile time it takes a case and for error testing. count (nl) and the count number of addresses to be used to resolve DO-CASE offsets and a value to use for error checking (n2). n --- (run-time) --- nl n2 (canpile) RANC;E-CASE Used in a colon-definition in the nl n2 --- ( run- t ime) form: n _-- addr n (canpile) n(1l 00-CASE ... n(2J CASE ftpl ... END-CASE Used in a colon-definition in the (fp) ... END-DOUGE form:

nil) EO-CASE ... n(2) nf3) RANGE-CASi ItpJ At run-time it consumes the value on ... LWD-CASE (fp) ... LND-DO-CASE the stack to be used later by case statements. This is used to ini- tialize a do case field. See CASE At run-time a canparism of n(1 ) and for its use. the inclusive range of n(2) and n(3) is done. If there is a match the At compile-time DO-CASE leaves a true part (tp) is executed, then case count (nl) and a value for execution resumes after END-DO-CASE. error testing (n2). It must be preceded by a DO-E. n(2) must be greater than or equal to n(3) to do a successful case.

- (run-time) At compile-tb RANC;E-CASE canpiles a branch and reserves space for an nl addrl nl --- addrZ n3 n4 (compile! offset at addr. addr and n are used At run-time it is used to terminate by ENDUSE to resolve the offset a CASE or RANGEUSE statement. See and for error testing. CASE or RANGE-CASE for its use. EXAMPLE OF L6E: At mmpile-time it takes a value for an error check (nl), an address SCR # 29 is an example of the use of (ddrl) to resolve an offset and a DOUSE. It shows the use of CASE, value that is the nunber of cases. RANGEUGE and null or rot-case. In It leaves a valw for error checking order to use it type in SCR # 19 (n4) , a value with a new case count first then SCR # 29. It is used by

FORTH DIMENSICXS II/3 Page 58 typing a number, then EXAMPLE. The FIG NORTHERN CALIFORNIA result will be a comparison of the MONTHLY MEETING REPORT number you typed and the comparisons done in the DO-CASE.

ADWAGES AND DISADWAGES: 28 June 80

The main disadvantage is that FORML Session - 00-CASE uses the return stack like Do ... DPdoes. This means that a Tom Zimmer described the product of value can not be passed on the his last two weeks effort - tinyPASCAL R-stack from the oiltside of the (written in FORTH, of course). Two of DO-CASE field to the inside or his remarkable routines include the use vice-versa. Also this means that if of Ragsdale's table structure (C.F., the loop value I is to be used it Morse code tutorial, 24 May 80 FIG Meet- must be on the operation stack ing) in a Tokenizer and his technique before entering the CO-CASE. of recursion uning dummy pointer-vari- ables. The PASCAL design Caue from a The advantages of this CO-CASE are "Byte" (Sep-Nov 78) series of articles that it has a RANGE-CASE and the which instructed the reader to do it in ability to allow the concept of not BASIC. Tom's first version of PASCAL- or null-case. This allows it to be under-FORTH occupies some forty blocks. used for something like an input entering routine for mrnething like FIG Meeting - an editor. The CASES can be used to prescan for special keys, the Three technical talks were deliv- RANGE-CASEs can be used as a capi- ered. Michael Perry described a CP/M tals only routine and the null-case File System written in FORTH which gives used to do the normal entry. a 8080/280 version of FORTH compatibil- ity with and use of extant CP/M data files. Dwight I(. Elvey Kim Harris spoke about arrays, i.e. Santa Cruz, CA 94065 how tables are created by alloting space to named variables and accessing array Judge's Comments - components by manipulating an index. Bill Ragsdale discussed database This entry performs the functions concepts after FORTH, Inc. ' s poly- of the FORTH-85 CASE statement. It FORTH and the organization of fields also provides compile-time syntax within files. Their FORTH definitions checking, allows a range of indices to and demonstrations of file manipulation be treated as a single case, and offers "How to talk to mass storage". a "none-of-the-above" case. Announced was the availability of source code for FORTH on the 6809 run- Compiling the same list of run- ning under SWTPC's FLEX 1.9. This is time words for each case results in copyrighted by Tallrot and is available excessive space overhead (about 28 from FIG for $10. See order blank. bytes for each IWZE-CASE). Defining Regarding FIG organizational busi- some new run-time words would save ness, two volunteers were asked to step space without adding much execution forward - one to organize meetings, time. sequence schedules and distribute tasks (Ragsdale estimates 3 hrslmo effort Also, using - O<" to cnec# the needed) and the other to take up the index against a range gives the wrong meeting announcement effort. result if the subtraction overflows. ;s J.ay Melvin

Page 59 FORTH DIMENSIONS II/3 =A CASE IMPLEMENTATION= A sample of use is: : TEST ; Motorola 6800. At compile time . The address of this nu1 cell 2. To provide a direct exit from is left on the stack. Finally, CASE> any executed CASE to the next resolves all addresses on the stack to program statement. itself until the opening nul is enwun- &red . 3. To provide an ELSE (or Trap) statement within the CASE structure. CODE (SASE) 1 T1¶90 ASSC(I8LCR I I )+ S C CWPARE ARGUMENT TO STACK I Please note: in both my 990 6800 0- IP s INCT I INCT ( wp STACK ENTER PRCC I and CUE I ) I nov f SET UP BRANCE AODR I implementations of FORTH TYCN NEXT all compiled addresses : *cut \ wuc) mcac o , mc~cROT I I are 16 bits. No relative I 0, 32 WORD NUM8ER , : addressing is used. : i~c\ (CASC) t, acne o , I I CCASC 0 'CASE : IIIMEDIATC I CUE 'CLSC 'CASE : IMMEDIATE The canpiling word 'CASE creates a 8 WC> BEGIN PCRE SWAP ! 7DUP 0- END : IMllLDIATE dictionary entry as follows:

1. The code address of (CASE). A dictionary map of the campiled 2. The source argument to be source would be as follows: canpared. This eliminates the compilation of LITERAL and the necessity of moving the argent to the stack.

3. The branch address for I when not true. This is the address of the next CASE statement in the list.

A canplete CASE statement requires three unique words:

, pronounced "case closed."

FORTH DIMRGIOS II/3 Page 60 FIG NORTHERN CALIFORNIA While using byte offset addressing MONTHLY MEETING REPORT for the branches would have saved .one or two bytes per CASE statement, to do so would violate the definition of word aligned dictionary established at the 26 July 80 recent Standards Tean meeting. FORML Session - The word incorporating the CASE paragraph is entered with any 16 bit Henry Laxon presented his string value on the stack. Any CASE statement package which has been his first FORTH finding the stack equal to its argument programming effort. He pointed out that pulls the entry from the stack. If no this package was designed for a comput- CASE statement matches the stack erized type-setting task and not text parameter the value reinains for the editing. The word "string" takes a ELSE statement, if used, or beyond the length parameter and name and is mani- "case closed" point. pulated so to find, concatenate, parse, move and so forth. ?his procedure executes (and curt- John Cassady then outlined his piles) nicely on the byte oriented string package which he fashioned after Motorola 6800 by using the following Northstar's BASIC. He pointed out it's definition for (CASE). file handling utility and a discussion arose regarding screen windows, input

CODE ICASPI ( N6800 APSENBiEfi I windows and video segmentation. Amaz- I LDX 0 1 LOX N STX , SA'VE ARSLflC!I': 1 TSX 0 ) LOX N CPX ?SUPA?C TO STACX I ing how FORTH gets strung along. 0. IP A P'JL B PUL t ?OP STACK 8 I LOX INX INX INX INX I EKTER PROC ' use I LDX 2 I LDX I SIX 4 SE': BRAIICH I FIG Meeting - TREY NEXT

Announcements included the report Thank you for the opportunity to of over 25 attendees at Kim Harris' Hum- submit this. I think the contest idea bolt State FORTH class. is a great one. How about some future Allyn Saroyan described the prob- contests on +mP, the Bartholdi "To" lems he's had trying to convert code concept and/or Data Structures. If from other machines and asserted that publication space pmits I'd also be we ought to submit code along with interested in a competition an SORT its algorithm and perhaps eveu assemb- and/or an approach to precompiled, ler particulars. relocatable FORTH for virtual memory Don Colburn, from Creative Solu- processing. tions, mentioned a FOKTHcoming tutor- ial under CP/M with stackgraphics. Bob Smith reviewed progress and William S. Emery problems of the floating point stand- Costa Mesa, CA 92626 ards team effort . John James described Cap'n Soft- ware's Apple editor. Bill Ragsdale spoke briefly about Judges' Comments - This entry the Installation Manual version editor achieves its objectives with only 7 and code was shown on how to extend short and well-factored new word FORTH, Inc. 's editor. definitions. The CODE word could have A preview copy of the August 1980 been written in high-level. While Byte magazine was passed around. See having to specify the case keys as the order form to get your copy. numbers at mpile time is a restric- tion, it is adequate for many applica- ;s Jay Melvin tions. Ard it does simplify the source code. APPLE - 4th CASE Case Docunmtation- The CASE statement format is !-.Lv. Fittery as fol1.m:

The result. of :.re 3EGIN-CASES, Here is 3 ;E-iect case fxApple-4th. EN'D4XX.S is: The Apple t;?:-ks so-far and allows any le-~elcjf ::2s+-incj of any of tne allow- i 0 ii 3 JGE o;t~Jn 15 cxecuttd able str-&ztdros plus more BFLIN-CASES, 1 1 if no CASE option is executed END-CASES. You will qet a lot of fai13r.c.s it do not balance your ?f n

Note: The general approach of the CASE . =-=.I@ W-E" ; statement is : : NEC .'I ESC-CIZ-N" ; : IEC .I@Esc-crL-L" ; :TEST 5 DYER = IF DROP .I' FIVE ELSE : SK .I0 ESC-CL-S" ; 6 OVER = IF DROP ." SIX 'I ELSE : Esc KEY 7 OVER = IF DROP .'I SEVEN" ELSE BEGIN-CASFS DGQP .'I SAD INPVT" 27 CASE ESC-W END-CASE THEN THEN THEN ; 14 CASE EX END-CASE 12 CASE IEC ENDCASE Generates the same code as: 19 CASE SEC END-CASE

: TEST END-CASES : BEGIN-CASES : OVTm 34 CASE 34 . END-CASE BEGIN-CASES 35 CASE 35. ENDCASE 27 CASE Esc END-CASE 36 CASE 36 . ENDCASE 14 CASE 91 DOT ENDCASE DROP ."BAD INPUT" 12 CASE 92 WT ENDCASE Rm-cASEs ; 19CASE95DCrr ENDUSE DOT Note: You must use up so if no case is ENDCASES ; executed as if is left on the stack.

MRTH DIMENSION3 II/3 Page 62 i : MONITER BEGIN KEY DUP OUTPUl' : OVER= OVER = ; 32=END; : CASE BACKSLASH OVER= ;S BACKSLASH ZEDBRANCH HERE 0 BACSLASH IXOP ; INMEDIATE Figure 2. : ENDUSE BACKSLASH BWHHERE 0 , SWAP HERE 2 - SWAP ! ; IMtEDIATE : Esc-Esc ." Esc-EsC" ; : ENPCASES BEGIN -DUP IF HERE 2 - SWAP : slx .I* Esc-m-S" ; ! 0 ELSE 1 THEN END ; IMMEDL4"E : LEC .Ig Esc-cTL-L" ; PRINT-QFF : NEC .IV Esc-cTL-N" ; 85 85 PLIST : omm ( GNERAL 8-BIT SELECT CASE CODE 1 B EGIN-CAS ES ( NEEDS BACKSLASH ( \ ) TO PORK 1 27 CASE KEY ( NR 16 BIT VERSION SEE # S 1,2,3 1 BEGIN-CASES : X%X IF ELSE THEN ; 27 CASE Esc-ESC ENXXSE 'XXX DUP @ SWAP 2 + 4? 14 CASE NEC END-CASE ( X1: 2 BECOElES 1 IN THE ABOVE LINE) 12 CASE LM: EM).CASE FORGET XXX 19 CASE SEC ENDCASE C0Ns"C BWH CDbSTA" ZEIIO-BRANCB ENPCASES : BEGIN-CASES 0 ; IMMEDIATE ENDCASE : OVER= OVER = ; 14CASE91IWT ENDUSE : CASE BACKSIASH OVER= 12CASE92DOT ENDCASE ZERO-BWH , HERE 0 19CASE95DOT ENPCASE BACKSLASH IXOP ; IMMEDIATE m : ENlFCASE BRAKH , HERE 0 , END-CASES ; SAP HERE 2 - SWAP ! ; IMMEDIATE : MONITER BEGIN KEY DUP OUl'PW ( W2: 2 BECOMES 1 IN THE AEKIVE LINE) 32 = END ; : ENDUSES BEGIN -DUP IF HERE 2 - S?W ;S ( X3: 2 BECOMES 1 IN TffE WVE LINE) ! 0 ELSE 1 THEN END ; IMMEDIATE

SuDDort Words

:COT0 'Sl+l!tYPEDROP; : '? MRD HERE COWEXT @ @ FIND ; E. W. Fittery : LITR>2+DUP>R@2+; International Cereputers : .PFE'ICH R> R> 2 + DUP >R @ 2 + SJAP Mount Arlington, W 07856 >R ; ;S

Judges' Comments - Interesting but rather 1hi ted . : NKSLASH .=ETCH 2 - , ; : BRANCH R> 2 + @ >R ; : ZEK)-BRANCH O= IF R> 2 + @ >R EISE R> 2 + >R THEN ; : BEIN-CASE3 0 ; IMMEDIATE COME TO FIG CONVENTION NOVEMBER 29

Page 63 FOXl'H DIMESIONS II/3 -DO-CASE EXTENSIONS= certain values of the DO-CASE variahlc, and a ccmnon mutine for all the other cases. This closes any "loopholes" fDr Bds Ciles erroneous values that can occur. Viis is easily implemented by putting the Upon using the DO-CASE structure comnon routine after the last END-CASE offered by Rick Kain in the Vol. 1, and before the END-CASES in Rick's No. 5 issue of Forth Dimensions, I DO-CASE structure. However, for came acrass several instances where readability and documentation, I the pwer of this tremendously useful defined a dummy word, OTHERWISE , construct can be improved. The first (i.e. : OTHElWISC ; XMCEDIATE) , to mark is where several options are defined the action. Making this work an using the CASE and END-CASE structure, IMMEDIATE word assures that run time is but all remaining cases have a cmon not affected. CITHERWISE must be used option. The other feature is where the at this particular pint in the DOXASE DO-CASE variable is to be tested within structure, and has no meaning or usage a certain range of values instead of anywhere else. strict equality to one value per CASE. In order to maintain symmetry, some The need to test for equality to a renaming of the keywords was neces- value within a range leads to the sary. The old structure looks like CASES structure. Nhereas x CASE tests this : the DOUSE variable (VCASE) for x = WE, lo hi CASES tests KASE to see E0-c if it satisfies lo < VCASE < hi. If w CASE...... ENDE KASE is within the range of-the lower x CASE...... END.CASE boundary, lo, and the higher boundary, ... hi, then the appropriate statements are ... executed within the CASES. ..ENDXASFS z CASE ...... EI-JD-CASE statement (this is the newer word - END-CASES don't confuse it with Rick's END- CASES). If VCASE is out of range, fly structure looks like this: these statements are skipped and execution resumes after the ENHASIS UO-CASE (new word ) statement. a CASE...... END-CASE b c CASES...... END4XSES !he listing of the structure is in ... the figure (see enclosure). The minor ... changes include - changing the name of J CASE ...... i3ID-CME EM)-CASES, making a dmy word called k 1 CASES ...... WD-CASES OTHERJISE, and defining the new word m CASE...... END.CASE CASES. OTHmg IS E ...... END-OO-CASE The simplicity of CASES does not reflect the time it took to get it The lower case letters indicate wrking. (A fairly lengthy interactive operations that leave a 16 bit value on Forth debugger was written to help with the stack. CO-CASE is symnetrical with the developnt). The basic idea is to END-DO-CASE, CASE is symmetrical with subtract the upper limit from VCASE END-CASE, CASES is symmetrical with minus one and see if the result is zero END-CASES and OTHERWISE, well.. .. or positive (i.e., the carry flag IS set). If the carry flag IS set, then OTHERWISE is useful when there the result is out of range and the are several courses of action for Forth instruction pointer (kept in

FORTH DIMENSIONS II/3 Page 64 to the intent of extended segment by the BC pair) has to be increnented as so the use of a name. My advice to other that the next "instruction" executed programmers is to use this jump around will the one after END-CASFS. The be feature very sparingly, as to remain action is the Same as when KASE does 93 in keeping with the concepts of struc- not match in the statement. If CASE tured progrmirq the carry flag is EWT set, then VCASE . is less than or equal to the upper bound and possibly in range. If The TEST for the new DO-CASE is KASE is less than the upper bound, the listed on screen 153. It differs from lower bound is subtracted from VCASE. the program that Rick submitted in that If the result is negative (i.e., carry the various variables are to be entered is I" set), then KASE is out of range on the stack before executing TEST. possibilities and IP is increment4 to resume after mis way, all 65,536 can be tried instead of only the 128 END

I AFTER-END-CASES leaves an address on the top of the compile time stack Judges' Caments which is assembled into the dictionary - by JMP in code CASES. At run time, the More of an extension of previous this AFTER-END-ES segment serves as work than a new an extension to machine code in code CASE. CASES. Although this type of progrm ming is a OrrO type of construct, it is used here to keep the definition of code CASES short. It also adds insight

Page 65 E"H DIMENSIC)& 11/3 SCREEN 150 0 ( DO-CASE STATEMENTS 4-4-80 BG ) 1 BASE ce 2 VOCABULARY FORTH+ FORTH+ DEFINITIONS 3 4 ( DO-CASE CASE END-CASE CODE DEFINITIONS ) 5 0 VARIABLE VCASE 6 CODE DO-CASE H POP VCASE SHLD I INX I INX NEXT JH? 7 CODE CASE W POP VCASE LHLD L A MOV W 1+ CMP 8 O= NOT IF I LDAX I 1+ ADD A I 1+ HOV NEXT JNC 9 I INR NEXT JflP THEN H A MOV W CMP 10 O= NOT IF I LDAX I 1+ ADD A I 1+ MOV NEXT JNC 11 I INR NEXT JMP THEN I INX NEXT JMP 12 CODE END-CASE I LDAX A L MOV I INX I LDAX A H MOV 13 H PUSH I POP NEXT JMP 14 BASE C! :S ( END CODE DEFINITiO1JS ) 15 ( COPIES FROM FORTH DIMENSIONS Vl-5 pg 50/51 BG 4-4-80 )

SCREEN 151 0 ( DO-CASE EXTENTI3NS 6-2-80 BG ) 1 2 CODE -TOP H POP XTHL XCHG E A FlOV CMA A E MOV D A MOV 3 CMA A D nov D INX D DAD RET 4 (NOT TO BE CALLED FROM HIGH-LEVEL) 5 CODE AFTER-ZND-CASES 0 LDAX C ADD A C HOV NEXT JNC 6 B INR NEXT JMP 7 8 CODE CASE VCASE LHLD H DCX XCHG ' -TOP CALL 9 CS IF D POP ' AFTER-END-CASES JMP THEN 10 VCASE LHLD XCHG ' -TOP CALL 11 CS NOT IF ' AFTER-END-CASES JMP THEN B INX NEXT JMP 12 13 CODE END-CASES I LDAX A L YOV I INX I LDAX A H MOV H PUSH 14 I POP NEXT JMP 15 :S

SCREEN 152 0 ( CASESLOTHERWISE EXTENSIONS 5-22-80 BG ) 1 ( FORTH+ DEFINITIONS - COMPILER DO-CASE STATEMENTS ) L 3 : DO-CASE COMPILE DO-CASE HERE 0 0 , ; IM!.!EDIATE 4 : CASE COMPILE CASE SWAP HERE 0 C, : IHMEDIATE 5 : END CASE COMPILE END-CASE HERE 0 , SWAP HERE 6 OVER - SWAP C! : IMMEDIATE 7 ( COPIED FROM FORTH DIMENSIONS V1-5 W 50/51 BG 4-4-80 ) 8 9 : CASES COMPILE CASES SWAP HERE 0 C, ; IMMEDIATE 10 : END-CASES COMPILE END-CASES HERE 0 , SWAP HERE OVER - SWAP 11 C1 : IMMEDIATE 12 : OTHERWISE : IMMEDIATE ( NULL DCFINITION ) 13 : END-DO-CASE BEGIN HERE SWAP ! -DUP 0 END ; IMMEDIATE 14 FORTH+ ;S 15

SCREEN 153 0 ( TEST FOR EXTENDED DO-CASE 5-22-80 BG ) 1 BASE CO HEX 2 : MONITOR DO-CASE 3 40 CASE QUIT END-CASE 4 41 CASE ." AAAA " END-CASE 5 42 CASE ." BBBB " END-CASE 6 43 CASE ." CAT a END-CASE 7 30 39 CASES ." NUMBERS " END-CASES 8 OFE 102 CASES ." CROSS END-CASES 9 OTHERWISE ." NOT TESTED 10 END-DO-CASE : 11 12 : TEST BEGIN DUP MONITOR 0 = END ; 13 14 BASE C! ;S 15

FCR"Ii DItlD4SIONS II/3 Page 66 ENTRY FOR THE FIG CASE CONTEST Now the 'OTHER' has compiled a drop for the m and ENDCASE does not Ar ie Ka t tenberg compile a drop. In both the above examples we can An Overview of the CASE Statement nest other case structures in any of the case bodies. This is another Externallv the CASE statement looks reason for using 'OTHER' sometimes. 1ike : Though this is in m way essential mn CASE ESAC to the above structures I have cbsen ...... a high level branch in the condi- k CASE ...... ESAC .. .. tional branch that is compiled by .. .. CASE (1.e. (CASE) manipulates the .. .. return stack contents to effectuate a .. .. branch). Now it is simple, machine .. .. independent and self explaining to make .. .. wrds like: 1 CASE ...... SAC >CASE

(>CASE), (

there in a more advanced example. Finds 'true' or 'false' on the stack. It fetches the address of the The m, n, k, p here are compiled second return stack number which is the literals, but there may be all sorts of pointer (stored IP) in the list where a FORTH compiled there. branch can occur.

- If 'true' was on stack, the pointer is incremented by 2 (making next skip to the CFA following the Source definitions in fig-FORTH words branch) and the second stack nunber is dropped. (It was the 'key' to the 'case'.)

- If 'false' was on stack, the pointer SLl ':a0 is incremented by the value that is . :*SL control structure M-8Ofeb29 I . SMM (Ir-level branch if 801 il zero, um.d by CASE *) found in the location where it is .-WI- 1+ SWAP If SUAP-DROP Z-CLSL DUP @ @ IBLN SWAP 41 ; pointinq to (makinq NEXT to resume :ma ( Complete a pnd~nqforward branch .I interpretation of- the list where 11111 OVER - SWAP I : CASE1 (Complied by CASE, do a test and conditionally branch *I the branch was compiled at a new OVER .I ZBRAN I L :A.SSC (~xecuceunttl LSAC it 1.7-2 quais caser~0) location). 7CcllP CWPILL (CCSL) ULRL 0 , 5 ; IIIIICDIATL " SAC (Clome CWCi Key 11 left If case not done.) I ?PAIRS e C~PILLnmwcn BLRL o , SWAP corm 4 I IM~ATC mBR 121111 (rrtor laat EsM. if stack or nemted CASES umed tture - 4 7 ?AIRS CWPILC DilOP 6 I IIlllLDIATC - Finds an address on stack: a dis- tance from the actual DP value to that address is compiled in the address. n 1.31 (CASE 1 8 aLcontrol structure ~-8oreb29 I CYXUE (Clome a Cut? control mtructure *) DOP 4 - If CmPILE DROP LLSE 6 ?PAIRS 4 ZULN Finds two numbers on stack, canpares Bccm WP 4 .I SP~CSP @ < AND ll1U DROP COBR these leaves the on stack. =PUT I IMEDIATE and 2nd -1 Then control is transferred to ZBRAN. k The CF'A of (CASE) appears in canpiled 9 lists as a relative branch (the rela- - tive jump following it in the list).

Has precedence and checks whether se are compiling when we use it. It cunpiles (CASE) and puts the address following (CASE)'s CFA in the list, on stack. It stores a temporary 0 in that location and puts a 5 for COME TO FIG CONVENTION pair checking on the stack. NOVEMBER 29

WRTH DIMEXSIONS II/3 Page 68 ESAC Glossary entries for each word - in sheet B Does a pair check on the 5 it expects from CASE. It compiles a puts a temporary in the ZBRAN mf --- (if f is true) BRANCH, P mf m (if f is false) location following that BRANCH and puts -- the address of that location on stack. Procedure to perform the branch for The branch that is half made by the a high level run time conditional branch in a CASE control structure. previous CASE is completed. For pair check by the following a 4 is ENDCASE If f is false (zero), the in-line pt on stack; change check digit the of following the compiled (from 5 to 4) makes the nesting of parameter reference to the run time conditional other case structures in CASE SAC .... branch is added to the stored inter- possible. (ESAC has precedence. ) pretive pointer (second word on the return stack) to effectuate a branch. OTHER

precedence, it does pair check If f is true, 2 is added to skip the Has in-line parameter and is dropped. on the 4 it expects from ESAC. It m compiles a DROP for the key (for the Used by (CASE), (>CASE), (CASES) CASES that are all not fulfilled when etc. this point is reached). The check digit 6 is put on stack. The change COBR addrl -- from 4 to 6 as a check digit signals to ENDCASE that the 'OTHER' is used and it Calculate the branch offset from makes nesting of other case structures ddrl to HERE and store in addrl, thus in OTHER .. . . ENDCASE possible. resolving a pending forward branch. (CASE) rn n -- (if in equal n) c2 m n -- m (if m unequal n) Checks for a 4 on stack; in case there is a 4 the "(?I'HER" is not used The run time procedure to condition- ally branch in a CASE control struc- and we must compile a aROP here. If there is not a 4 there must be a 6 ture. (which is checked); it is replaced by a 4. If m equals n, no branching occurs and NEXT interprets the words follaWing the branch offset in the dictionary The rest of ENDCASE looks for I 4's on stack that are placed there by after the CE'A of (CASE). the previous SAC'S (since there may be 4's on stack already before the If m is unequal to n, m remains on stack ad WXT resumes interpretation definition that contains the case I structure. ENDCASE also checks SP@ with a new interpretive pointer value against CSP contents). according to the branch offset.

The incomplete branches from the Canpiled by CASE. For branching, ESAC's are completed until none is 2BWH is used. left .

Page 69 F"lM DIHEMSI~II/3 CASE m n -- (run-time, if CASE ...... ESAC m equal to n) P,C2 CASE ...... €SAC m n --- m (run-time, if ...... m unequal to n) CASE ...... SAC -- addr c (canpile) OTHER ...... ENDCASE

Occurs in a colon-definition in At run-time ESAC executes after the the form: part selected by the CASE it pairs to. SAC branches over the following cases CASE ...... ESAC and resumes execution after ENDCASE. CASE ...... ESAC ...... At compile time ESAC compiles a CASE ...... SAC BRANCH, reserving room for a branch E"3E offset at addr2, leaving ddr2 and c2 or : for later resolving of the offset and CASE ...... ESAC error checking. ESAC also resolves the CASE ...... ESAC pending branch fran the previous CASE ...... at addrl, storing the ofset from addrl CASE ...... ESAC to HERE. Ol'HER ...... ENDCASE UTHER m --- (run-time) c, p At run-time CASE selects execution cl -- c2 (canpiling) wsed on an equality test of the two numbers on stack. If m equals n the Occurs within a colon definition part until the next €SAC is executed in form: and then control is passed to after the ENDCASE. If m is not equal to n, m CASE ESAC remains on the stack and control passes ...... CASE ...... ESAC to after the following SAC. The use ...... of OTHER and its 'other' part are CASE ...... ESAC Dptional. ENDCASE, or ( if present) OTHER ENOCASE JTHER, drops the remaining m...... At run-time OTHER executes when At compile time CASE compiles none of the cases is met. UI'HER drops :CASE) and reserves space for an the m against which the cases were 2ffset at addr. addr and c are tested. Jsed later for resolution of the affset and error testing. At compile time OTHER compiles a DRDP. OFHER also checks the cl fran SAC addrl cl - addr2 c2 the last SAC for error testing and (mpiling) P,C2 puts c2 on stack to signal ENDCASE that UI'HER has been used and to make nesting Occurs within a colon-definition of new case structures possible between Lq the form: OTHERand ENDCASE. CASE ...... ESAC ENDCASE addrl cl addr2 cl ..... CASE ...... EAC addrn-1 cl addr-n c2 -- ...... (=wiling) PIC CASE ...... ESAC m -- (run-time, no OTHER used) ENDCASE zr : Occurs in a colon-definition in the form:

KFt'ITl DIMENSIOS II/3 Page 70 CASE ...... ESAC CASE ...... ESAC sca :io3 ...... 0 ( Caamples of CASE control structuce AK-BOle429 CASE ESAC 1 I CWPL 3-e :rat IS pticted, releccrd by num&ur -1 C numbrr -2 2 5 CUE 12 CASE .. This' CS AC ENDCASE 3 1 CASE ::.. CSAC 4 QTIiEl .. only' EWDCASE ESIC or : 5 18 CASE 2 CASE .. a very' ESAC 6 7 cwc :1illy' ESIC CASE ...... ESAC 7 OTaR .* example' ENDCASE ESAC a OTPER 2 CASE :Of the use. EShc CASE ...... CSAC 9 9 CASE .. of nrrtcd' ESAC 10 OTUER .' Casrs' EHDCISE E::DCljE ; ...... 11 12 I s CASE ESAC 13 14 CYI'HER ...... ENDCASE 1s

At run-time ENDCASE Serves as the destination of all forward branches Short discussion on the case from the SAC'S in the case structure. statement presented here If OTHER does not occur, ENDCASE drops the m that remained on stack when no case is met. The history of this case statem?nt At compile time ENDCASE compiles is outlined below: a DROP if OTHER was not used in the case structure, which can be known fran A first try for CASE was a regh03- the value of C2. ENDCASE resolves all ment of IF so we could produce case the pending forward branches from the structures 1ike : SAC'Sby storing the offset from addri to HERE in addri for addrl thru addrn. The Cl's indicate the presence of such Ia. ... CASE .... THEN ... an unresolved branch as long as the ... CASE .... "4 ... control stack pointer is not passed. ... CASE .... THEN DWP ... or ib. ... CASE .... EfsE Exa.nples of the use of this statement ... CASE .... ElSE ... CASE .... ELSE DROP THEN THEN THEN

SCR Di02 0 ( Examples of CASE contic , sttucture AK-0OI.b 29 I At run-time, Ib is the faster 1 a ¶EL *it t number -1 krwea 0 and 9 as teat *) 2 0 CASE .. I IAC one since no other cases are tested 3 1 CASE .* I IAC 4 2 CASE : IAC once a case is aone. A disadvantage s ~CASSI : I iAC 6 4 CUE .. I IAC however is the necessity to write the I IAC I iAC TIEN ...... series. I LAC 10 0 CASt .. ElghC. kAC 11 *.CASE .* IIUE. FAC An improvement on Ib was to organize 12 . OUt8id. range 0-9 CUDCASE t 13 the DROP THE3 THEN ... THEN by a new 14 1s - mpiler wrd : 11. ... CASE .... ELSE ... CASE .... ELSE ... CASE .... ELSE ENDCASE

Page 71 FaRTH DIWSIW II/3 But since ENDCASE can only see CASE (after all, why should one not be by the 2's for ?PAIR on stack how allawed to do this) and the number is many branches have to be completed. this not in the way as far as I can see. structure I1 cannot be nested inside . . . IF .. . ELSE .. . THEN or inside an The use of a high level (CASE) and other CASE ... ELSE. the use of the separate ZBRAN there are not mandatory. 'Ibis could be avoided by making a new "ELSE" and then using other numbers To have a fast executing case for ?PAIR checking in the structure. structure one may rewrite (CASE) in low level without affecting the essence of By changing the number for pair this case structure. checking in the new "ELSE" (ESAC) , also nesting in other case structures is However, as presented here the possible : structure is machine independent for standard fig-FORTH's. 111. ... CASE 7 PAIRS .a. CSIC '?PAIRS 'b' .. . CASE UAC ... CASE EIU Also this high level (CASE) makes it ?PLIRS .b. ENDCASE easy to extend the possibilities, e.g. : Now, a remaining problem is the i (>CASC) 0-9 < tBRAti : (JRANCB IF SNALLER THAN1 part between ESAC (the last) and t >CASE COMPILE (>CASL) UERE 0 , 5 : IRNEDIATE ENDCASE. There the number against which the cases are checked is still on and we have a new type of case. stack, so we cannot easily manipulate the stack there: also, at compile time or: we have the "b"'s for ?PAIR checking on t (CASES) ROT >R 1 < SdAP R > &ND R> stack so we cannot nest a new case SWAP ZBRAN ; (BFANCB IF NOT I1 RANGE1 structure there. : CWCS COHPILC (CASES) BCRE 0 , 5 ; :NIILDIATE

To solve these two problems we made etc. Any odd case you expect to use the optional "OTHER" that performs the more than once can be incorporated in DROP at run time and that at canpile the set and used just like CASE. time changes again the "check number" to inform ENDCASE that the DROP already has been compiled and to make nesting of other case structures possible. P.S. In rereading all this I notice that "?COHP" is not needed in the Of course the nesting problem could definition of CASE; please omit. have been solved by using an opening word like is done in the example on P.P.S. My native language is Dutch; page 50 and 51 of Forth Dimensions, please forgive me any errors in the WA. 1, No. 5. But this forces the use language. of an extra word at compile time. This opening word &uld e.g. store the top Arie Kattenberg stack word on the return stack (not in Utrecht , Netherlands a variable as is done in the example!, since this prohibits nesting of case Judges' Comments - This entry has a structures). But I doubt whether it is number of interesting ideas in it and an advantage to remove the number could be useful to developers. The against which the cases are checked presentation is a bit hard to follow in from the stack: This costs (run)- time, places. A plus is the short history of makes it difficult to change that the developnent of this CASE structure number between an ESAC and the next through several earlier forms.

FaRTH DIMENSIONS II/3 Page 72 =CASE CONTEST STATEMENT= begins compiling the list and ) is introduced as a wrd, in addition to George Lyons its role in ccmments, to terminate the list. Different words ccc( perform different functions involving data This entry submitted to the FIG or code stored in the list. The Case Statement Contest is 1imi ted parenthesis was defined as a word to providing a compiler syntax for because of the similarity of the run writing equivalents of ALxx)L ''case" and time process of skipping around data "switch" statements in FORTH and some embedded within a definition and the additional words to use in conjunction ccmpile time skipping past a canment in with WLstyle case expressions. As source code. The general approach such it does not solve all the problems compiles all lists with an execution posed in the contest announcement. address at the front which processes the data and returns controls to In formulating a case expression the point following the list; the syntax the first decision was to treat address of this return pint is stored case lists as in-line or literal immediately following the execution expressions within : definitions rather address at the begiMing, and it has than provide a special defining wxd mre uses than just returning control. creating words of a case list type. When a list contains variable length This increases flexibility of use at elements a vector of addresses of the the expense of storage saving otherwise elements is appended to the end of the obtainable by exploiting the code list in reverse order. The case lists address field of a case-type wxd. A are an example of this structure in second decision was to allow use of a hich the data is a list of variable list either to execute a case selected length code segments, written for at run time or +a compile the execution instance using EXECUTE( CASE case 0 address of the case--for use in more de... CASE case1 code... CASE .. . 1. complex mpiler features. Storage for The case compiling words such as a list which was to be only executed EXECUTE( are written using utility turned out less than when mpiling so bbrds available for building additional different commands are provided for functions along the same lines. these two circumstances. A third decision was to include in the canpiled Examples of the latter are some code for a case list no number-of-cases Words that might be used in conjmc parameter; hence no checking of the run tion with EXECUTE( ... ). These are time inputsubscript's validity is done mentioned briefly here, and some are in executing the cases. Instead implemented in the glossary and code separate mrds ?INDEX and EXCEPT are section. provided to do this checking, taking more storage when used than if their [ n ] EXCEPT EXECUTE( ... ) functions *re built into the case list (manpile time sxrce) de, but saving time and space when they are not needed, as when the At run the EXCEPT. will check the validity of the input is established subscript on the stack intended to elsewhere in a program. select a case in EXECUTE(...) and replace it by zero if negative or The in-line case lists are handled greater than n. Case zero can ther?. be as one instance of a general approach especially written to handle these to in-line list functions in which a exceptions. list is represented in the form ccc( ...list data... ). cc( is a Word which W+ addr n --- addr+2*n

Page 73 FaFETH DIMEXSIm II/3 Address arithmetic operation for At run time ?INDEX will issue a byte addressable computers. Increments system error message if the subscript an address adr by n words. Can be on the stack intended to control implemented in machine code using shift EXECWE( is invalid, instead of writing oprations instead of multiply. a special case zero in the case list.

:w+2*+;

W- addr n --- addr-2 fn II:ID( nl , n2 , n3 , ...I EXECirrCl ...

Address arithmetic operation for byte addressable computers. Decrements an address adr by n words. See W+. FIND( is another example of the in-line expression approach Hhich performs the inverse of a simple COMPILES addr n PIc -- vector. It searches at run time for a Used in conjunction with EXM=VTES in match to the stack item in the list, a : definition to combine a procedure returning either its subscript or zero performing canpiler operations with run if not found. Again, case zero can be time code for the procedure canpiled, written to handle the exceptions. in a single definition. In the form : ccc .. . COMPILES .. . EXECUTES ... ; IMMEDIATE , ccc performs the operations up to EXECUTES at compile time; these INTERVAL( nl , n2 , n3 , ... nk ) compile time operations include COM- EXECUE( ... ) PILES which compiles the address of the code following EXECUTES. EXECUTES places at that address a pointer to the code for : definitions, so that the code following EXECUTES is in effect a Another in-line expression type , : definition without a name field. l"ERW( contains a vector of values in ascendirq order dividing the number domain into the intervals between :CWPtLGS ICCt4P CWPILC Co((P1LG BERG n 2 ALLOT I IMMEDIATE them. At run time a subscript is returned identifying the interval in which the stack item falls, and the ExECmS addr n --- PfC item itself is preserved for processing by the selected cdse. See COMPILES. Compiles ;S to terminate the canpile time part of a dual definition, and stores the address of the next dictionary location in RANGE( nl , ml , n2 , m2 , ... 1 the space reserved by COMPILES. EXECUTE( 0.. ) Canpiles the address of the code for : definitions to begin the rm time part of the word.

I CXEC~ES?CmP L KERC 7 - I Co(l?x~C IS n 7mI1S aEnE SNAP I COIOILC 1 c , I 1 IX~~CDIA~E

n I ?INDEX EXECWE( ... ) (cunpile time source)

FORTH DIMENSIONS IX/3 Page 74 Similar to INTERVAL( except that an in-line data structure begun by each n,m pair defines a separate BEGIN(. addr0.. . is a possibly empty range, and a subscript is generated list of addresses of points internal to identifying the first range found which the data block left by other compiling embraces the stack item, or a zero if Words; if present it is appended to the outside all of the ranges. data in reverse order. me address of the location following the data is then n MENU ccc EXECUTE( ... ) ; stored back at its beginning point addr. Also resuiis compilation nde. MENU is a defining Word to create a menu-driven application named ccc which : ) n 7PARIF LEGIN - DuP WHILE , R~PEA: n ?PAR:S ';EKE S~AP at run time will present screen n to 1 I I If4P!LDIATE the user, who will select options by entering a number, which is finally LIT( --- processed by the case list compiled within ccc. Used in Words processing in-line data structures to set up the return Glossary and Code and computation stacks for accessing the data and branching around it. The The implementation below is written Word in whose definition LIT( appears entirely in high level code assuming a must be used immediately in front of an byte addressing machine. Literal "n" in-line data block, so that the address used with ?PAIRS is left unspecified of the location at which to resume for consistent specification of all control is found in the following ?PAIRS values. location; see BEGIN(. Consequently on entry to LIT( the return stack contains BEGIN( --- addr n ff n the address of the code following LIT( itself on top and the address of the Used in certain compiling words to data block just below. LIT( replaces begin compilation of an in-line, or the second return stack item by the literal data structure within a : address of the code following the data, definition. The next word in the and pushes the address of the first dictionary is reserved for the address data item onto the canputation stack. of the location following the entire Also see )LIT. structure, to be filled in by ) at : LIT( R> R> DUP Cd >R 2+ SWAP >R ; address addr. n is for canpiler error checking. ff marks the stack so that )LIT -- other canpiling words may push pointers to internal parts of the data block, to Similar to LIT( except returns on be appended to the end of the block by the computation stack the address 1. see ). of the last word in the data structure instead of the first wrd, for access- : BEXIN ?CCMP HERE n 0 2 ALurr . ; ing any address vector stored there in reverse order by ). ) addr n ff addr0.. . n -- (when used as a Word) : )LIT R> R> @ DUP >R 2 - >R i Has two entirely different uses. EXECUTE( --- addr n ff n (ampile) P,C Cne terminates a comment begun by (, in n -- (run time) which case it is not processed by the compiler. When used outside of a Used within a : definition to define cominent it completes compilation of a list of routines, or cases in high level code in the form:

Page 75 DIMENSIONS II/3 Used to begin each high level LXCCWtE( CASE CascO... :S CASE Caaql... IS .a- ;s 1 code case in a case list defined by CCMPILE(. Dtecutes CASE and compiles !it run time case n is executed and the address of the code for executing : control returns beyond the list. definitions. The routine begun by Ynpredictable results occur if n is :CASE should be terminated by ;S as in not a valid subscript at run time. EXECWE ( expressions. Executes BEGIN( at compile time. t :CASE [ milt 2 - 1 [COnPILEI CASE I CcnPILE [ 3 , I ; II~IIEDIITC ~XLCLTE:( ?COI(P conpxLcs BESIN( EXEC~ESILI: w- 9 >R : IMLDIAX CODECASE addr n ff addrO... n --- zALL( --- addr n ff n (compile) PIC addr n ff addrO...addrl n P n -- (run time) Used to begin each assembly code Similar to EXECUTE( except the case routine in a case list defined by routines are in assembly language in rorlPILE(. Executes CASE and mpiles the form CALL( CASE caseo... CASE the address of the next dictionary zasel...... ). Invokes the assembler location (as in the code field for a vocabulary and suspends canpilation. CODE definition). Compilation is suspended and the assembler vocabulary :ALL1 7CMP CONPILES BES1:II LCMPILil [ : COMPILCI ASSEMBLER CALL(. A NEXT LItCLlLS ILIT Id- @ SPI 2 - SUAP DROP OX5CWEi IMMEDIATE invoked as in jump to within a machine code case will resume high level execution following the case XE addr n ff addrO... n -- list. addr n ff addrO...addrl n P I CODECASE [CMPILEI CASE 2 ALLOT UERE DL'? 2 - ! [CaPILC] I [COIIPILEI ASSCH8LLR i IMXLDiATE Used to begin each cae in a case list defined by EXECUTE( or CALL(. LITERAL( addr n ff n (compile) Mds the address of the next case addrl --- nl -- n2 (run time) P,C to the list of case addresses addr0.. . cxl the stack? using n for error check- Used within a : definition to define ing. a vector of 16-bit values. These values be made Word execution : CASE n HERE n : IMMEDIATE may ?PAIRS addresses using the form 2CMPILE( addr n ff n (mile) PIC -- LITERAL( word0 word1 word2 0.. 1 n -- addr (run time) be made literal numbers using Used within a : definition to of may the form define a list of routines, or cases in either machine code or high level code LITERAL( [ nO , nl , n2 I I 1 rn the form COMPILE( :CASE ... ;S ...... ZODECASE ... ) which returns at run At run time the element whose sub- execution address of the case time the scription is on the stack is returned hose subscript is on the stack. The (without checking the validity of the :nput subscript must be valid or stack value). When used with E3(EcuIIE mpredictable results will occur. lb in the form LITERAL( ... ) EXECWE the actually compile the execution address same result is achieved as using returned use also EXECWE( ,. See and EXECUTE( ... ) except that storage LITERAL(. Compiles using BEGIN(. requirements are less because no extra addresses are needed at the end of the vector. Uses BEGIN( to compile the list. :CASE addr n ff addrO.. . n -- addr n ff addrO... addrl n P

mTH DIMENSIONS II/3 Page 76 Case Contest Entry George Lyons :LITERAL( ?CWP CONPILES BEGIN( CXECVTCS LIT( W* ? ; IflUEDIATE APPEND1 X EXCEPT n (compile) --- CDlPILES :CASE 2 --- The wrds and above n (run time) P,C share a common function which myht preferably be in a separate Word by Used before an in-line case list or itself. That function is compiling literal vector def in& by EXECUTE(. ) .. mto the next dictlondry location the or similar Words, in the form [ n ] code address used in : definitions. EXCEPT. Compiles an execution address Rather Wrd, and the value n, presumed to be the than define a new however, number of caes or vector elements in this function may be added to ttl.e the subsequent in-line expression. ,it existing definition of the : operator, run time replaces any input value that as the function tc be performed when STATE is the canpiling mode, in con- is negative or greater than n by zero, allowing case or element zero to trast to the regular function perforrned represent the "exceptions." This my when STATE is the execution mode, as be an error message or other explicit it is hen a definition is begun using operation, or may simply bypass the :. Similarly, the word CODE can be entire case list by leaving case zero expanded to include a function to be empty, i.e. compiling high level cases performed in the compile state which as ;S and machine rode cases as a jump consists of compiling the code address to NEXT. The EXCEPT function is not of a CODE definition (the address of built into the case list expression the following location.. .), setting code itself to allowing saving the STATE to execute and invoking the storage when it is rat needed. ASSEMBLER vocabulary for beginning assembly language programming med- I CXCCPT >R COUPILLS R) , EXECXES R) DUP 2+ >R OVER O< IF iately following. Revised definitions DROP DROP 0 ELSE $ OVER < If 2ROP 0 ENDIP ENDIF : INIIEDIATE fran the case statement glossary above would then be: FIND( --- addr n ff n (Lapile) nl -- n2 (rm time) P,C : EXEC'XES ? CSNP CmPILE ;S n ZPAIPS HERE SUAP iCQlPfLE ' . IflflEDIATE Used in a : definition to define an array similar to LITERAL( but to The Words :CASE and CODECASE are eliminated for CfXPILE( perform the reverse operation at run and the syntax is : time, 1.e. the value is on the stack and the subscript is returned, or zero if not found. CCePILE( CASE : ...high level Case..:S ... 1 cmnLE( CASECOX ...ia~n.ne cde case... . I

George Lyons I"ERVAL( -- addr n ff n (mpile) P,C Jersey City, tU 07302 nl --- nl n2 (run time) Judges' Canments - George got off to Used in a : definition to define a literal vector of interval boundary more problems than CASE, 1.e. pints in increasing order; at run time in-line machine code by the subscript of the snallest boundary There are numerous ideas here, dese above nl is added to nl already on the mg of further analysis and examples stack, to control a subsequent case CASE. list processing nl. Compiles using BEGIN ) .

: IICTCRVAL CQlPILES BLGIN( (CWPILEI I EXECVTES 1 LIT( OVER OVER R 2 - DO I OVER I I < IF LLAM ENDIF 1 *LOOP SWAP DROP SUAP - 1 1 : IMCDIATC

e 77 =A FORTH CASE STATEMENT=

R. D. Perry

The Case Statements presented here are an extension of the FORTH Il? Statement. The structure of the CASE SCR 0 83

Statement is such that it allows an 0 ( WRE CASE RDP 800322 I N-way branch as contrasted to the IF 1 : BEGIN-CASES ?CmP 0 4 ; IRREDIATE 2 statement two way branch. 'Ibis version 3 : CASE itat? ( CL,~) 4 ?PAIRS I EL I 4 CQ(?ILE NHBMNCU HER5 0 , I EL,WL I allows a CASE to be tested against a 5 5 ; IMCDIATC ( LL, :m.s ) 6 single value or a range of values. It 7 : RANGC-CASC ?CWP ( EL.4 1 4 ?PAIRS ( EL I 8 CWPILC NRAl1GE~I)RAEICB WERE 0 , ( EL.NnL I does not require contiguous values for e 5 I IMEDIATE ( LL,NBL.~) the tests. The value or range of 10 11 I CLSC-CASE ?CWP 4 ?PAIRS ( EL 1 values to be tested against are deter- 11 CO((P1LI DROP 0 5 I IIUCDIATL ( CL.O.5 ) 13 --> mined at run-time, this allows vari- 14 ables to determine CASE selection. No 15 preprocessing is required as with the vector selection approach. It will execute faster than an IF statement preceded by preprocessing (Example: = KR a4 IF ) assuming code implementation of 0 I luwc CASE RDP 000322 ) 1 I END-CASE KMP 5 ?PAIRS cmpxu DMKN ( CL.DL I N=Branch and MIANGE=BRANCH. 1 WP 1 cL.aL.8L. I J xi-icic -i+ -ov~R.-SWAP I ( CL I 4 CLSC DROP 5 TUN UCRL SWAP , 4 ( NCL.4 t ; IMCDIATE I became interested in the CASE & Statement while implementing a CRT 7 I CND-CASU 7CmP 4 ??AIRS ( CL I 0 DO? 0- 0- 1 7PAIlt ( ERlOR IF NO CASES I Screen Editor for FORTH Editing and 9 conmu DROP 10 BLGIW DIJP Word Processor use. ii nxu DU, 8 SNAP icnC OWI - SWAP ! 12 RC?UT DROP t IMCDIATC ;S 11 i YLllCI 01 STACK ITEMS I ii i~ Yiwo LINK NLL -> NEW END LINK 15 BL -> BCGXW LINK mL -> NCN DCGIN LIIK XI I ei 0 ( CASE STATLflENZS RDP 800322 1 1 EfX 2 CODE N-BRANCH ( XI BCT NOT EOU SEC BRANCR FROM 1NL:NC LITERAL I 3 INX, INX, rE ,X LDA, BOI CflP. 0- 6 I?, rr ,X LDA. DOT i+ cap. 0- 3 IP, INX, INX, ' ODRANCH I ( BUMP ) JMP, 6 ENDIt: 7 ENDI?, BMNCll JRP, C; aca 0 05 I 0 ( CML STAZUICI? TEST RDP 000320 I 9 cooc Muffic-nmNcn ( IF TEIRDnm BMNCB rRou LIT I 1 I ml? BCGXNYCS 10 INX, INX. INX. INX, SEC, rc ,x LDA, 801 SBC, a 1 CML tMC. WD-CMC 11 r~ ,x LDA, nm I+ SIC, o< NOT 3 a we TWO. EYYMC 12 XI, SEC, nm LDA. TE ,x sac, no1 i* LDA, I? ,x SBC, o< 4 9 UffiC-CASP > ICG. TCN AND < TEV CND-CASC I?, IYX, INX. OBMNCB 8 ( 8UIP I JMP, CNDII, ENDIC, BRANCB JHP, C: 15 DECIMAL -->

SCR t '12

2 ( CASE STATERCNTS RDP 800322 1 --> I mow :YIS LINE xr CODE VERSIONS NOT USED I 2 DCCIMAL- I R IS POINTING TO NEXT WTIOll I 3 : R-BRANCH 4 OWR - 5 XI R> 2* >R DROP 6 CLSC I> DUP 0 + >R 7 TREY ; 8 9 t NRANGE=BIUNCH 10 no1 DUP ROT ( L.V,V,H ) > 11 I? SWAP CROP R> DUP I3 + >R ( OVER RANGE 1 12 CLSC DUP ROT ( V,V,L 1 < 13 I? R> DDP 6 >R ( UNDER RANGE 1 14 ELSE R> Z* >R DROP ( IN WNGC I L5 ?BEN THEN ; -->

FORTH DIMENSIONS II/3 Page 78 N=BRANCH nl n2 -- (run-time, 1-11-2) values on the stack. If they are nl n2 -- (run-time, nl<>n2) equal signalling that the CASE is to be executed, bth nl and n2 are dropped The Eun-Time procedure to conditionally and execution proceeds through CASE. branch. If nl does not equal n2 the CASE. If they are not equal only following In-Line parameter is added to N2 is dropped and execution skips the interpretive pointer to branch to just after END-CASE. ( See BEGIN- ahead (or back) and n2 is dropped. If CASES ) nl equals n2 the interpretive pointer is advanced passed the in-line para- At Compile-Tine CASE canpiles N=BRANCH meter and both nl and n2 are dropped. and reserves space for an offset value Compiled by CASE. at addr2. addrl is the address for the offset value of the last END-CASE. nl M?ANGE=BRANCH nl n2 n3 --- and n2 are used for error testing. (run-time, nl>=n2 & nl<=n3) nl n2 n3 -- nl RANGE-CASE (run-time, nln3) N1 N2 -- N1 (Run-Th, Nl<>N2 ) P,C2 N1 N2 -- (Run-The, N1=N2) The Run-Time procedure to conditionally addrl N2 -- ddrl addr2 N2 (Canpile-Time) branch. If nl is less than n2 or nl is greater than n3 the following in-line At Run-Time selects execution bases on parameter is added to the interpretive whether nl is in the range n2 to n3 pointer to branch ahead (or back) and (n2n2) END-CASES to signal that the last case nl n2 --- (routine, nl=nl ) was an ELSE-CASE. nl and n3 are used addrl N1 - Addrl Addr2 N2 for error testing. (mpile time) ELSE-CASE -- (run-time) At Run-Time CASE selects execution addrl addr2 nl --- based on equality of the bottom two addr3 n2 (-pile time)

FORTH DIMENSIOIS II/3 NEW PRODUCT .ic Run-Tune causes execution to Skip after END-CASES. ( See BEGIN- XSES ) pic0 FORTH

It Zompile-Time uses ADDR2 to set the :::set of the last CASE or RANGE-CASE HERMOSA BEACH, CA, JUNE 24, 1980 :> point to after this END-CASE. picoFORTHTM, a new subset of ,railes BRANCH with an offset to be (disk :3;calated later by END-CASES. The pOlyFORTHTM, is available for 1802 -xiition for the offset of the last or PROM) and 8080 micro- processors. Designed for interactive evaluation, 3D-E is temporarily stored in this affset location and the new offset picoFORTH includes all the essentials for programming, debugging, and testing location is put on the stack. N1 and N2 are used for error testing. a single-task application. This complete operating system features the polyFORTH assembler, compiler, text interpreter, editor, disk utilities, and DJD-CASES basic documentation. picoFORTH can be -- - (run-time with ELSE-CASE upgraded at any time, either for a n --- (other run-time) single purpose (with one or more of addrl nl -- (compiletime) three ackages: Source, Target Compilerk, or Mulititasker) or to full At Run-Time drops a stack value if o polyFORTH. A File Management Option ELSE-CASE exists. Any END-CASE will package is also available. In addition continue execution just after the to the current versions, picoFORTH will DROP. ( See BEGIN-CASES ) soon be implemented on the 8086, 6800, and LSI-11 processors. Price for At Compile-Time DROP is compiled and picoFORTH is $495. Write or call Tom at all of the offsets from an END-CASE FORTH, Inc., 2309 Pacific Coast Highway, are calculated and stored in their Hermosa Beach, CA 90254 (213) 372- proper locations. ADDR is the location 8493. for the last offset for an IXD-CASE. 'hat location holds the address for the prior offset and so on. The first NEW PRODUCT offset location blds a value (0) which tells END-CASE that there are no more offsets to calculate. ALPHA MICRO FORTH

R.D. Perry San Diego, CA 92106 This system implements the Forth Interest Group language model, with full-length names to 31 characters, and extensive compile-time checks. Judges' Comments - This is quite a complete and well documented entry. In addition, the diskette includes The range-of-cases feature is well an editor, a FORTH assembler, and a done. Note that high level alterna- string package, in FORTH source. The tives are given for the 6502 machine PDP-11 FORTH User's Guide, which CODE words. includes extensive annotated examples of FORTH programming.

This FORTH system runs under AMOS. The distribution disk is single density. The complete system price is $190: Professional Management Services, 724 Arastradero Road, Suite 109, Palo Alto, California 94306, (408) 252-2218.

MRTH DIMENSIObS II/3 Page 80 CASE STATEMENT

The case structure by R.B. Main looks very powerful and flexible, but it seems to me to be unnecessarily complicated. My suggestion is for a word that does OVER = IF for his word You will see that /=BWH does tke CASE. This fits the existing FORTH same as OVER = IF and the case struc- compiler very well. The example by ture could be implemented without Main muld read introducing /=BRANCH but I think speed and clarity better if one adds a CO? : MONITOR word as I have. 41 CASE .I1 ASSIGN THEN 44 CASE .'I DISPLAY It THEN 46 CASE .I1 FILL " THEN 47 CASE ." CO I' THEN 53 CASE .I' SUBSTITUTE " THEN W.H. FokR11 ELSE .I' INSERT Sawbr idgeworth DROP ; Herts. a21 !3N3 mD You will note that I have made the ' insert' message unconditional. This illustrates just how little need be added to the present EWRTH structure and also bw use of the present FWrlli Judges' Canments - Bill Rnel1 didn't conditionals can be harnessed to the sutmit this as a contest entry, but it simple case structure as above. "he ameared in our mail just as the normal FORTH syntax blds, and can be &test started. we took the libex relied upon if case structures are of including it as a mini-Case appre nested into other structures, or into priate for the 6502. another set of case conditions. This structure is neither the optimum for speed nor bytes. On the other hand we should avoid adding to FORTH in such a way that the ----HELP WANTED ---- I nucleus and compiler grow any more than necessary. I favor a CASE structure that makes the program clearer, encourages sound software PROGRAMMER FOR MAJOR PROJECT design and adds power to the language Orange County, CA Location without adding significantly to the system software overhead. Call or write: ANCON 17370 Hawkins Lane Using the fig-FORTH model I need Morgan Hill, CA 95037 ideally one more nucleus word, and one (408) 779-0848 for the compiler .... COD1 /-sRMcn I Branch if SrC - IOT wn-r*co) IYX. INX. ( Drop DOT o?ly) BEE, IC ,X LDA, 0 ,I SIC, IMI 0- CPD, PV ,X LDA, 1 ,X SIC. ' 6-0 0- ISD, IUIPt JHP. I -1 ( nl n3 --- nl Car. Is emcutad Lf nl - nZl CQIPILC /-IIuIUI UERI 0 , 2 ; IHHCDIATE

Page 81 A CASE STATEMENT= ENGLISH EXPLANATION Only two new words need to be Major Robert A SelZer defined to use the CASE statement. (CASE) is the execution version that OVERVIEW OF THE STAT" duplicates ( OVER ) the top of stack value then compares ( = ) it to the CASE - The "CASE" statement is a case value. If they are equal, the special form of the IF-ELSE-THEN that true action through the IF statement is permits the selection of one of many taken and the stack value u is dropped cases depending upon the top wd on ( DROP ). As part of the true action the stack being equal to a specified a flag ( 1 ) is pushed on the stack word (the value that precedes "CASE"). for OBRANCH to test when CASE is executed. If the stack and case values u ( stack value ) ul ( case value ) are not equal the false action ( ELSE ) CASE ( true action ) ELSE ( false is taken and a false flag ( 0 ) is action ) THEN pushed on the stack over the original stack value tested ( u ). Both actions u ( stack value ) ul ( case value ) exit with THEN. CASE compiles the CASE ( true action ) THEN address of (CASE) and the address of the run-time IF called OBRANCH . If u = ul, drop u,u1 and execute true A 16 bit zero is compiled ( , ) at action following CASE until ELSE or HERE in the dictionary, by HERE 00 THEN. Otherwise, drop ul but leave u , to reserve space for the branch to on stack and execute ELSE ( false ELSE or THEN. The precedence bit of action ) or ?HEN if m ELSE. Imple- CASE is set so that CASE compiles 6 mentation is the Same as IF-ELSE4", bytes whenever it is executed. Like however each subsequent use of "CASE" IF, CASE must be used inside a colon will Save 2 words ( 4 bytes ) cxer the definition and each use of CASE explicit use of OVER = IF DROP. CASE requires a corresponding THEN ( or use also improves the readability of ELSE ) to complete the structure. the surce and if used often, will save code as well as being more convenient GlDSSARY ENTRIES to the user.

SOUFCE DEFINITIOIS The run-time procedure that is used see attached source listing. Note by CASE, Equivalent to OVER = IF mop. that fig-FORTH word COMPILE should (CASE) is canpiled by CASE. replace FORTH, INC. word ( back- slash ) or X (in later FORTH, INC CASE u ul --- U P,C2+ versions) and a 16 bit anplace word ( axma ) replaces the 8 bit emplace u ul CASE true action for u=ul C, ( C-comma ). So, for SCR # 198, EISE u false action THEN line 6. The fig-FoRTH definition for CASE would be: If u=u1, drop u and ul and execute true action following CASE until next ELSE or THEN. If u is not equal to ul, drop : CASE CWPILC (CASE) CMPILL OBIUNCU HCRL 00 , I InncmArt ul but leave u and execute false action following ELSE or drop ul but leave u if no ELSE and exit to THEN.

E'CRT€I DIMESICRG II/3 Page 82 applications like the example shown

u ul CASE trur actlon tor U-ul ELSE in SCR Y200, the 2 byte overhead in u u2 CASE trur action for u-ul ELSE u un CASE trur action for u-un ELSE CASE ( 6 bytes vs. 4 bytes for IF ) U f.lm action THEN THEN. ..THEN saves 4 bytes for each use in lieu of OVER = IF DROP ( 10 bytes ). More importantly, its use significantly enhances the readability structure EXAMPLES and of the murce code at the minimum cost of only 2 new FORTH mrds. See screens #199 and #200.

SCR #199 is used to demonstrate SCRO 198 simple CASE use in the same application 0 ( CASE DEFINITION MS-09FES8O ) 1 FORTH DEFIIITIONS SASE P HEX FORGET TASK : TASK : of the example published in FORTH- 2 DIMENSIONS v 1/5, p. 51 to show 3 4 : (CASE OVER - IF DROP 1 ELSE 0 THEN i ( EXECmION CODE 1 conformity to an existing structure. 5 6 : CASE ICASEI OSRAwCtl BERE 0 C. i INREDIATE 7 8 BASE I SCR #200 is a simple, but elegant 0 10 example of CASE use in a video editor 11 12 which occupies about 355 bytes of 13 14 dictionary space for the COMPLETE 15 _____ editor. This is a good example of the SCR) 199 CASE structure in fig-FORTH used to 0 1 TEST a CASE * SZRLCTURE I BASE P SEX save code space provide clarity of 1 and 2 : HONIMR structure. While the editor is written 3 41 CASE .' ASSIGN ELSE b 44 CUE .: DISPLA! ELSE for the m-3A terminal, line 1 defines 5 b6 CASE . PIL! ELSE 6 41 CASE .* GO ELSE a word which controls the cursor 1 49 CASE .. INSERT * ELSE 8 53 CASE .. SUBSTITUTE - ELSE position sequence, so that any terminal 9 THEN THEN THEN THEN THEN TREN : can be used by making appropriate lo 11 : KEIBOARD BEGIN KEY 71 AND DUP NONITOR 20 END ; changes to the word YXCUR The 12 . 13 SASE I :5 integer values in line 2 ( 2 and 4 ), 1b determine the initial Y,X offset of the 15 cursor in the HOME position (upper XR# 200 o ( vmo EDITOR, COPYRIGHT RCS 1978 REX 00 VARIABLE cull left corner + Y,X offset). This 1 : TICUR 18 ECRO 30 ECHO 20 + ECHO 20 + ECHO ; ( ADM-IA) allows for adjustment of different LIST 2 : .CUR CUR @ (0 /HOD 1 + SUAP 4 + SYA? PXCUR : : ICL'R 0 MAX 3 3C1 RXN CUR I I I +CM CUR P + LCM i : +.CM

Page 83 2.4 CASE FORTH 338 2 0

A CASE STATEMENT= Executes the word whose address is contained in the array (SO) at cell location n (Sl). Kenneth A. Wilson Example: n name CASE

CASE STATEMEW CONTEST 3.0 Explanation of the Example in Screen 339. 1.0 Description of the entry (coded in microFQRTH) 3.1 Line 1 defines 3 Cases: 1.1 Screen 338 defines the 4 words 3.1.1 FIRST is a Case of 4 cells needed generate a complete to 3.1.2 SEC is a Case of 4 cells CASE statement. 3.1.3 THIRD is a Case of 4 cells 1.2 Screen 339 contains a CASE test 3.2 Lines 2 thru 5 define "print- example. ing" words as follows: 1.3 The next 2 pages contain the printout obtained by executing *3.2.1 PronO~ns: I, YOU, WE, 'IHEY word 3.2.2 Verbs: RLRJ, WAL, SIT, JOG the TRIAL. 3.2.3 Adverbs: HCXlE, BACK, CXXJN 2.0 Definition of CASE words UP stack word vocabulary block in out 3.3 Line 6 thru 9 define the --- contents of the three Cases as follows : 2.1 FORTH 338 0 1 3.3.3 THIRD Case contains 4 A redefinition of for Visual Adverbs clarity. Pushes onto the stack the address of the parameter field of word that follaws 3.4 Lines 10 thru 14 define the the TRIAL which when executed, in the current input word stream. will cause the three Cases to be executed in sequence for. 2.3 =CASE FORTH 338 3 0 each different possible com- bination of the index. 1.e.: Puts the address of a word (Sl) into an array (SO) at cell n 111 FIRST CASE SEC CASE THIRD CASE 112 FIRST CASE SEC CASE THIRD CASE Example: n word array =CASE 554 FIRST CASE SEC CASE THIRD CASE Bad "n" becanres "wrd" in as: 555 FIRST CASE SEC CASE THIRD CASE "array" case.

KRTM DIMENSIONS II/3 Page 84 An Overvtec TRIAL

Cell number n I RUN iiO?IE WE I RUN 3ACK I RUN DOWN Reserved for future U1. I RUN UP

UOR D 1 YOV RUN HOME WORD2 YOU RLid BACK YOU RIJN DOWN YORDn YO'.' i

Figure 1 WE ICUN HOME

A Case Array NAMC Of n+l Cells WE R(JN BACK KE RUN DOWN WE HUN UP

THEY RUN HOME Cell number 012 n TREY Rt3J BACK

"It THEY RUFJ DOWN THEY RUN YP

I WALK HOME I WALK SACK I WALK DOWN I WALK UP

Plgurc 2 YOU WALK HOME Storing and cxecutiq Cell 2 YOU WALK BACK YOU WALK DOWN YOU WALK UP

33# LIST WE WALK HOME 0 I CASL TEST UORDS) WE WALK BACK I DISPLAY DCFINITIONS a : : 4 : -cue ROT 2. + WE WALK UP 5 t CASE SWAP 2' + 6 7 THEY WALK HOME 8 9 THEY WALK BACK 10 11 THEY WALK DOWN 12 13 THEY WALK UP 14 15 DCCIML is KAY 2-18-80 31 I SIT HOME I SIT BACK 339 LIST 0 [ CAJC TtZST EXAHPLL I DISPLAY 0EFI.YITIOWS DKINU I SIT DOWN 1 4 I1 FIRST -CASE 1 -> RUN SCC -CASE 1 -> UOllC TSIRD 100 FIRST -CASC 2 -> WALK StC SASE 2 -> BACK TSIRD SASE 8 3 -> WC FIRST CASE 3 -> SIT SCC WYY TUIRD TBEY FIRST -CASE 4 -> JOG sec -cue 4 -> UP TBIRD SASE YOU SIT DOWN 10 t TRIAL CR 5 1 DO I 11 5iw1 YOU SIT UP 12 5 1 Do OVER OVtR I ROT ROT 13 CASE SLC CASE THIRO CASE cn 14 tooP DROP CR LOOP DROP CR Loo? t I5 DCCIML :S UW z-mao OK

Page 85 EORTH D-1- II/3 NEW PRODUCT h" SIT 1-1CME WE SIT BACK 68OOo WE SIT COwN CREATIVE SOLUTIONS, INC. announces \JE UP SIT the availability of the FORTH programming approach for the Motorola THEY HOME SIT 16-bit Microprocessor. THEY SIT BACK 68000 COWN THEY SIT Featuring: FORTH Interest Group THEY SIT Up Model and FORTH-79 Standard Compatibility, Virtual Disk Operating I JOG HOME System, Text Editor, Inline Macro I BACK JOG Assembler, Computer Aided Instruction I JOG DOWN Course on the FORTH Proramming Approach. I JOG UP Also Available: Customized 110 YOU JOG HCME Drivers for Non-Standard configurations, YOU BACK JOG Suitable Hardware Configurations, JOG WWN YOU Complete Source (written in FORTH), Meta YOU JOG UP Compiler, Multi-tasker, Extended Data Base Management and File System. WE JOG HCME WE JCG BACK The standard software product, WE JOG DOWN available for configurations utilizing WE JOG UP the Motorola MEX68KDM (D2) 68000 evaluation model with Persci 1070 THEY JOG HOME controller and compatible floppy disk THEY JOG BACK drives retails for between $1500 - $5000 THEY JOG DOWN (depending upon options) for single user THEY JOG UP systems. OK For further information please contact Creative Solutions, Inc., 14625 Tynewick Terrace, Silver Spring, Kenneth Wilson Maryland 20906, Phone: (301) 598-5805. Waltham, MA 02154

NEW PRODUCT Judges' Comments - This is a very simple positional (jump of table) type AVAILABLE FROM ANCON CASE. Ttte whole thing can be defined in three short lines of code. At first glance, however, the presentation looks The following manuals and other infor- mation is available from ANCON, 17370 wre difficult than it is. Part of the problem is that the notation - the word Hawkins Lane, Morgan Hill, CA 95037. names - does not suggest, very well, Write for detailed list. what is going on. This entry looks FORTH Systems Reference Manual like a good complement to Eaker's. The FORTH Language Both are simple mechanisms for doing a FORTH-11 Reference Manual single job and the jobs that they each Indirect Threaded Code Reprints do are very different. Work is needed FORTH, a Programmers Guide on integration and further developnent PDP-11 FORTH Users Guide of these models. PH21-MX FORTH Manual CYBOS Programmers Manual Program FORTH, A Primer The JKL FORTH Manual

FOR'III DIMENSIONS II/3 Page 86 CASE STATEMENT CASE n CASE m0 ml ... mi DONE WAYNE WITT/BILL BUSLER CASE is used as a structured con- struction here n = 0 to i and n0 Overview ml ... mi represent a list of word names with the list being terminated The CASE word provides the capa- by the word DONE. bility to vector to a particular word based on an input parameter, similar to When the definition containing the the FORTRAN computed geto. The CASE case construction is executed, word also provides automatic limit rodule mn will execute, then execu- checking on the input parameter with an tion will continue after the DONE. optional out-of-range capability If n is not in the range 0 to i, ( CYrHERCASE ) . execution continues after t5e DONE. Alternative CASE usage with OTHERCASE

n CASE mG m1 ... DL OTXERCASE ma WNE

b9 When the definition containing the case construction is executed 0 ( NEW CASE - CODE CASE IIV L WE 1/1S/80 ) MEX , I module mn will execute if n is in 2 cwi II r' P~LIJ NZXT ( ID - TOP O? STACX I 3 the range 0 to 1; then execution 4: (CASE) ( CODC CASE -- CASE PAPNIETCR N -1 i 5 I @ 7??? AND OVER SWAP (< ( TRUE I? N IN LIST RANGE I will continue after the DONE. If n 6 I? 2. I + 2+ Q 2+ EXECmE ( EXEC. LIST MODULE N 7 Cut DROP I @ O< ( TRUE IP OTBERCASE SPECI?ICD I is not in the range 0 to i, dule 8 II I e 7rrr AND 29 I + 2, e 2+ EXECUTE ( OTMERCASSC s TMEN WEN ( IKW TO CONTIMUE EXEC. AT WNE 1 nur will execute and then execution 10 I DUP e DUP o< ( GET ADDR. AND VALUE 01 CASE-INDEX ) 11 I? 7rl? AND 1+ TALN ( INCR INDEX I? OTIERCASE SPECITXED I will continue after the DONE. 12.~ a* 2+ + R> DROP 11 I ( CONTINUE EXECUTION AFTER WNE ) 13 14 ( NOTCI XNTERPRLTCR mxmcr NOVED TO END or LIST ORI Only executable modules should be ( MTER TEE WNC ) DECIMAL is IS usd in the case list; literals ad cmpiler words, especially:

CASE OF EISE THEN BGIN END BUILDG DOES so Should - be used. o I wew CASE - OTBERCASE - wm w 6 WE Z/~S/OO ) Rex 1 ( Pm CODE CASE ADDRESS IN DICTIONARY , 1 1 ( PUZ B ON STACX , I 3 t CASE (CUL) BZRE 0 , I IMEDIATE ( CREATE CASE-IUMX ) 4 ( IT DICTXOYARX AID ZERO I? ) 5 6 : OTMERCASE DUP 1000 SWAP I : IIIMEDIATL ( SET OTSLRCASC BIT 1 Used in conjmction With CASE word 7 ( IU CASE-INDEX I I for out of range conditions. See Y1 t DON8 WP BEDS SUP - I / 1 - ( CUC. CST ?OR CASE-12DEX ) 10, SNAP DO? @ ( GLT TMC CASE-INDEX TO =ST ?OR OTBRCASC ) CASE usage. 11 ROT DUP 0- ( TRUE I? UO ItWS IN LIST 1 12 I? DROP DROP 0 ( SET WE-INDEX 10 ZERO 1 13 ELSE SYAP I ma II menase sPccIrm I DONE 14 XI 1 - 8000 OR TMEN ( - -1 AND mencsc BIT SET I 1s TSEU SWAP 1 i IMEDIATC DECInAL is ( STORE CASE-INDEX I CASE word terminator. See CASE usage.

mi8 lirtinq is from a 6809 ror8ion of IORTE. I! n -- Replaces the interpreter pointer with the top stack item (n). t

Page 87 FORTH DIMESIONS II/3 MH2 illustrates the nesting capability of the CASE word. n --- This form of CASE conforms with the unwritten rule of FORTH to keep it me execution time portion of the simple and basic. The user needs to CASE word. remember only three words, CASE, OTHERCASE and DONE to construct simple << to complex forms of the structured nl n2 - f CASE. The CASE in providing automatic limit checking and out of range Unsigned 16 bit less than. recovery elliminates the need for user limit testing of the parameters. mis Example of CASE usage out of range chechng capability does slaw the execution speed slightly, but : TXX CASE TX1 TX2 7x3 DONE I it was felt that the added capability was worth the slight loss of speed. If TXX is executed, then execution will mntinue as follows based on the value on the stack. Bill Busler STACK VALUE ExEcm Odessa, Florida 33556 0 Tx1 1 TX2 2 Tx3 Wayne Witt Tamp, Florida 33615 Execution then continues after the DONE. If the stack value was not 0, 1 or 2 then execution continues after the DONE.

Examples of CASE usage with UTHEXASE. Judge's Canments - The run-time wrd I ma2 ~fiCASE LNQ '~ICL smc NULL ~KBLRCSE mi DONE t (CASE) seems much too long for the job t MKl CASE NULL FIFO TINC MIT-NSG OllfRCASC 11112 DONE ClCANOP : it does. This is partly haus the out-of-range case is handled by a special construction. Nevertheless, If MH1 is executed, then execution will the code could be reorganized or continue as follows based on the value factored. Also, pushing the DONE on the stack. address back on the return stack at the end of (CASE) would eliminate the need STACK VALUE ExM=m for I! and make the package more portable. 0 Nuu 1 FIFO The aOD0 ... THEN construction in Kitt 2 TIME &ak KR"H accanplishes all the same 3 XMIT-MSG functions much more efficiently. Any Other Value MH2 Execution then continues after the DONE, in this instance CLEANUP. COME TO FIG CONVENTION NOVEMBER 29

FolRTH DIWI~II/3 Page 88 THE KllT PEAK Glossary : GODO CONSTRUCT CDm --- addr n (mpile-time) P,C (GODO) n --- (run-time) Sy David Kilbridqe Used in the sequence The GODO construct, as specified in the glossary of the Kitt Peak FORTH ... 0l)DO RO R1 ... Rn THEN ... Primer, is a type of CASE statement.. An index on the stack is truncated to At run-time, OODO selects execution fall within a contiguous range and used based on a signed integer index. If to select a word from an in-line the index is <=0 then RO is executed; execution vector. I present here a if =1 then R1 is executed: ... if >=n very simple implementation in fig- then Rn is executed. After executirq FORTH. the selected reference, execution resms after THEN. As an example of usage, here is a word which accepts a 0 or 1 from the Discussion: The GOD0 construct terminal and selects the correspordinq provides a basic contiguous-range type disk drive, and rings the bell if any of CASE statement requiring very little other key is pressed. supporting code. The cumpile-time word is simple because mst of the work is

: GET-DRIVE .'I DISK DRIVE? 'I done by THEN. The run-time word is KEY 2F - simple because truncating the index 03Do BELL, DRO DR1 BELL, TIiEN ; allows out-of-range cases to be handled just like in-range cases. The necessary source definitions are If other means are used to insure that the index is always within range, : (0300) 2* the "catch-all" references RO &/or Rn OMAX Re4-MIN can be omitted. However, there is R> DUP DUP @ + >R still the time overhead needed to + 2+ @ EXECUTE ; truncate the index (unless (03110)is recompiled without the second line of : 03DO its definition). COMPILIE (0300) HEREo,2; The principal limitation of this MEDIATE construct is that only single wrds can be referenced. This prevents direct How it works: 0300 compiles (am) nesting of 03110's. HOwever, one can and leaves space for a branch offset to nest by defining the inner 03~0as a be calculated by THEN. ?he address of separate wrd and referencing it in the the cell and an error-checking flag are outer GXIO. By letting E40 ard/or Rn be left on the stack. At run time (0) such references, several noncontigwus doubles the index on the stack and ranges can be mered. truncates it both above and below so that the reference executed will always be chosen from the list provided. 'Ihen Kitt Peak PRIMER available from FIG (GODO) uses the branch offset to step for $20.00 in US and $25.00 Overseas. its return address Over the reference list and finally executes the selected reference. COME TO FIG CONVENTION NOVEMBER 29

Page 89 FORTH DIMEISIUS II/3 FIG NORTHERN CALIFORNIA MONTHLY MEETING REPORT words can define recovery and 26 April 80 error the return stack can be usefully unthreaded. He congratulated our Dutch The FN4L session consisted of three colleagues for their imaginative ;resentations covering FORTH File applications of "tricks" garnished from prcpsals. John James and John Cassady other mnputer languages. -1scussed Directories consisting of bit -32s named FileControlBlock (FCB) Henry Laxen was congratulated for aerein allocation of strings of blocks his excellent article on FORTH in the Files) were managed. Particulars of 80 April 28 issue of INFWW. z itflap manipulation at the Buffer, 51xk and Disk (file and volume) levels Kim Harris announced his FORTHming ere explicated. Some other concepts murse on FORTH programning at Humbolt ;xluded user transparency, hierarchy State Lhiversity (80 July 21-25) and :f directories, commands, security and also reported on a talk he delivered 12tegrity. Kim Harris described Record earlier this month at the Asilomar rqes and management within a File and I.E.E.E. conference on megatransistor ;Hve examples of FORTH, Inc. styled I/O chips. 3t the Field level. The pros and cons :f the various approaches will be ...HANDOUTS provided at the meeting debated at the next meeting where also included: String manipulation will be discussed. Attendees were requested to prepare -polyFQ?IW-CP/M (Brick) -ritten proposals of anticipated requirements and arguments for and -1NFWCftLD reprint (Laxen) qainst the different approaches. Tnough not a tutorial, the FORML -TIC-?aC-TDE (hFORTH, of Course) Sssion was very instructive. (George Flamer)

"he April Northern California FIG -overflow correction (Ragsdale) eting consisted of a presentation by :im Brick (of M&B Design) of a ply- -Match CW for 8080 figFORTH (anon) XRTH bootup under CPb. Jim described zne application requirements that -Double number support ( Ragsdale) -xduced the need and the technique he -sed to develop this bootup package -String match for Editor (Peter sold by FaRTH, Inc. He demonstrated Midnight ) me hybrid package on a "RS-80 with I/O accessories which allowed 8" disks and remapping of the TRS-80 memory for -z1~F~RTH-CP/?I comp tab il i ty. ;s Jay Melvin Bill Ragsdale initiated a tutorial 2n overflow correction which spon- -aeously escalated into a discussion XI error signals, repair and recovery. Kim Harris, Lafarr Stuart and Dave Publisher's Note: 3oulton described their respective approaches to dealing with errors. 3111 elaborated the "Utrecht approach" Cane on, you other FIGGEFG, send in t3 error signaling and recovery and reports on your meetings. We'll noted tw lessons learned: high level publish them.

PORTH DIMDSIW I1/3 Page 90 FIG NORTHERN CALIFORNIA MONTHLY MEETING REPORT the system was up and running for demonstration. Ragsdale notified us that Conpxlter magazine wants articles 24 May 80 for a FORTH issue next year and that Byte's August issue will have a mbert FORML Session - Tinney cover displaying three blocks in a field of stars, each block containing Kim Harris directed a review of last a word (2*, DUP, +) and threaded month's session to compare and contrast together by a ribbon terminating in a file systems presented by: space needle.

1. John James Handouts inclded: Kim's tool kit, 2. John Cassady Bill's Morse Code worksheet (a blank 3. Kim Harris (FORTH, Inc. system) page! ) , John's Version 1.7 brochure, and Benchmark by DRC for measuring The most striking difference between FORTH execution speeds on CRAY-1 the three file systems was that EVFVl'H, through micros. Also, a floating pint Inc.'s did not utilize a bit map in the package by NHC, a paper on file word directory which would allow for a concepts by Jim Berkey and the HomeBrew distinction between physical and Computer Club's newsletter by (ed. ) logical files. The bit map implemented Bill Reiling were available. in James' and Cassady's systems provide for easier file manipulation. ;s Jay Melvin

FIG Meeting -

Bill Ragsdale opened the meeting by introducing guests Ed Murray from the ----HELP WANTED---- University of South Africa and Don Colburn who is marketing a FORTH Full or Part Time Teaching Tutorial to configured for be MICROCOMPUTER various machines. R & D Technician Jr. Engineer The meeting was devoted to a two fold tutorial where Kim Harris ex- plained FORTH tools ranging from NICoutput ad base conversion to Tb assist in the integration, trouble- test interpretation. I/O formating shooting and design of microcanputer examples included the definition of systems for scientific and industrial HOLD, ASCII and PAD. These "tools" am1 ications. were applied in a temperature con- version program. Bill Ragsdale Programing interest a plus. followed with a presentation on problem solving techniques using the task of printing Morse (dits/dahs) characters to the screen in response to text E"H, Inc. input. Top down techniques were delineated by listing the subtasks and writing code then testing each module. Contact: Gary Kravetz FCRTH, Inc. John Draper described CAP" Soft- 2309 Pacific Coast tky. ware's Wrsion 1.7 FORTH for the Apple; Hermosa Beach, CA 90254 (213) 372-8493

Page 91 M%MH DI?IENsIoNs I1/3 FORTH Interest Group Meetings New York Various times Contact Tom Jung at (212) 746-4062.

Northern California Detroit 4th Saturday FIG Monthly Meeting , Various times Contact Dean Vieau at 1:OO p.m., at Liberty (313) 493-5105. House Department Store, Hayward, CA. Japan FORML Workshop at various times Contact Mr. Okada, 1O:OO a.m. President, ASR Corp. Int'l, 3-15-8, Massachusetts N i shi-Sh imbashi 3rd Wednesday MMSFORTH Users Minato-ku, Tokyo, Group, 7:OO p.m., Japan. Cochituate, MA. Call Fubl isher s Note : Dick Miller at (617) 653-6136 for site. Please send notes (and reports) about your meetings. San Dieqo Thursdap FIG Meeting, 12:OO noon. Call Guy Kelly at (714) 268-3100 ----HELP WANTED---- x 4784 for site. BLEINESS SYSTEMS IN FORTH Seattle Various times Contact Chuck P1i ske we need two good FORTH programmers. or Dwight Vandenburg at ( 206 ) 542-83 70. You should have solid FORTH experi- ence, a year or two, and be generally PotOmaC competent in Computer Science. Various times Contact Paul van der Eijk at (703) 354- We are building an exciting range 7443 or Joel Shprentz of business application systems using at (703) 437-9218. FORTH - the advantages are obvious! - and our approach is unique. We'll have Texas a range of configurations - single and Various times Contact Jeff Lewis at multi-processor, both Winchester and (713) 729-3320 or large fixed disks and color graphics John Earls at (214) screens. 661-2928 or Dwayne Gustaus at (817) Ideally you'll live in Orange County 387-6976. John - be attracted by a small, quality team Hastings (512) - and like to grab your own projects 835-1918. with a strong sense of self management Arizona - we haven't got the time or the Various times Contact Dick Wilson inclination to be overbearing. at (602) 277-6611 x 3257. Please send brief description of your background to: Oregon various times Contact Ed Kramnerer The Software Developnent Directxx at (503) 644-2688. 4861 McKay Circle Anaheim, CA 92807 and let us know why you think you'd like to work with us. MRTH DIMmIONS II/3 Page 92 Fc)RML is an organrzation (spons~red by the FORTH Interest Group) which promotes the exchange of ideas on CALL FOR PAPERS the use, modification and extension FORML CONFERENCE of the FORTH approach to systems developnent. This will be an advanced technical workshop; no introductory tutorials will held. (M=RTH f4dif icat ion Laboratory) be of papers must be received Papers are rerquested a three day Abstracts for by Octaber 1, 1980 for inclusion in the technical wrkshop t=, De held November conference prqrm. Complete pqers 26-28, 1980 at the Asilomar Conference be received by Ncjvember 1980 Grounds in Pacific Grove, California must I, (on the Elonterey Peninsula). The to be included in the conference purpose of the workshop is to discuss proceedings. Send Loth abstracts and advanced technical topics related to completed ppers to: FORTH implementatlon, language and application. Papers on any of the FORML Conference following or related topics are P. 0. Box 51351 Palo Alto, CA 94303 requested for presentation and dis- cussion : ----HELP WANTED---- 1. Programming methodology problem analysis and design TITLE : Product Supprt P rog rmr imp1enen ta t ion sty1 e developnent team management DVTIES: ResponsiDle for maintaining documentation existing list of software products, debugging including the polyFORTH Operating System Programming Language, file 2. Virtual machine implementation and arithmetic management options, math options and utilities and their documentation, address enlargement and providing technical support to position independent object customers of these products. code rnetaFORTH Pequirements for candidates:

3. Concurrency 1. Goal familiarity with FORTH-preferably resource management through one canplete target-mpiled scheduling appl icat ion. intertask conanun ication control and 2. Good assembler level programming integrity, privacy and skills. protection 4. Language and compiler 3. Assembler level familiarity with the typing and generic operations 8080 and PDP/LSI-11 processors and data and control structures preferably some of these: 8086, M6800, optimization CDP1802, NOVA, IBP! Series I, TI99G. 5. Applications 4. Excel lent cornnun ications skills--btn file systems oral and written; ability to work well string hand1ing with customers. text ed iting graphics 5. Excellent organizational ability. 6. Standardization Review and discussion of Contact: Elizabeth Rather 79 -STANDM EQRTH, Inc. Input €or the Standards Team 2309 Pacific Coast EWy. Hem= Beach, CA 90254 (213) 372-8493

Page 93 FORML CONFERENCE NATIONAL CONVENTION

(ElXl7-l Modification Laboratory) FORTH Interest Croup

November 26-28. 1980 at the Asilanar Conference Grounds, Pacific Beach, November 29, 1980 at the Villa California. A three day advanced Hotel, San Mateo, California, 8:30 a.m. technical workshop for the discussion - 4:30 p.m. for exhibits and papers; of topics related to KIRTH implementa- 6:OO p.m. cocktails; 7:30 p.m. for tion, language and application. No dinner (with speaker). This one day introductory tutorials will be held. convention will include presentations, workshops, hands-on equipment and a FORML is an organization (spons~red number of vendor exhibits. An evening by the FORTH Interest Group) which dinner will include a talk by one of promotes the exchange of ideas on the the foremost atlthorities on FORTH (mre use, modification and extension of the about the speaker in a later re- mRTH approach to systems developnent. lease ). Asilanar is a comfortable, rustic Preregistration for the convention resort located on the Pacific Ocean is available for $4.00. near Monterey in Northern California. Attendees are urged to bring family Pre-registration for the dinner ad members to Asilanar as they will enjoy speech is required by ktober 15th at the area and Thanksgiving dinner. $15.00. Costs are very reasonable, especially for families, and include roan (double Vendors may contact FIG about occupancy) and meals. the cost and availability of booth and table space. Attendees and/or par ti cipants $100.00 ( includes Tb preregister or for mre informa- conference registra- tion write: tion and materials) FWInterest Group Non-conference P. 0. Box 1105 guest (wife San Carlos, CA 94070 d/or husband, friend, and Vendors may contact my Martens at children 12 or (415) 962-8653 for details about over ) $ 75.00 exhibiting.

Children 11 Room arrangements can also be or yl3unger $ 50.00 made through FIG. Send request for registration ad list of guests by October 15th with a check to: ************FLASH LATE NEWS************ FCRML Conference FIG NATIONAL CONVENTION BANQUET SPEAKER P.O. Boor 51351 ALAN TAYLOR Palo Alto, CA 94303 Author of The Taylor Report for Computer World. 30 years in computer field.

Foc(TH DIMENSIOtS II/3 Page 94 FOATH UIrnEnSlOnS

FORTH INTEREST GROUP Volume II P.O. Box 1 105 Number 4 San Carlos, CA 94070 Price $2.00

Historical Perspective 1Publisher’s Col um n 96 - Balanced Tree

108 Letters

109 The Execution Variable and Array

11 I,I1 8,119 Meetings

112 Project Benchmark

113 IPS - A German FORTH-Dialect

The CASE, SEL, 116 and COND Structures Published by Forth Interest Group

Volume II No. 4 November/December 1980 PUBLISHER’S COLUMN Publisher Roy C. Martens

Editorial Review Board

Bill Ragsdale We’re deep into the planning and arrangements for Dave Boulton the FIG Convention and the FOAML Conference. If you Kim Harris haven’t made your reservations, call right away, we John James might be able to get you into the FORML Conference or Dave Kilbridge the Convention Banquet. Plan on coming to the Con- George Maverick vention anyway. Remember the dates and places :re.

FORTH DIMENSIONS solicits editorial material, FORML Conference, November 26.27,828 comments and letters. No responsibility is assumed for Asilomar, CA accuracy of material submitted. ALL MATERIAL PUBLISHED BY THE FORTH INTEREST GROUP IS IN FIG Convention, November 29 THE PUBLIC DOMAIN. Information in FORTH Villa Hotel, San Mateo, CA DIMENSIONS may be reproduced with credit given to the author and the Forth Interest Group. The other big news! FORTH-79 STANDARD is available!!! Call (41 5) 962-8653 or send in your order, Subscription to FORTH DIMENSIONS is free with today! $1 O.OO! membership in the Forth Interest Group at $1 2.00 per year ($1 5.00 overseas). For membership, change of Many publications are printing information about address and/or to submit material. the address is: FORTH. We don’t get them all, so please send in copies so we can thank the editors and add to our collection. Forth Interest Group P.O. Box 1 105 FIG had a booth at the Mini/Micro show and much San Carlos. CA 94070 interest was generated among attendees which carried over into a number of manufacturers that were exhibit- ing.

Membership is fast approaching 2,000. We now PERSPECTIVE have members all over the world including the People’s HISTORICAL Republic of China and Yugoslavia. See the listings of meetings for information about how you can form a FIG chapter. Just a few easy steps and you’ll have a time FORTH was created by Mr. Charles H. Moore in and place to share information. 1969 at the National Radio Astronomy Observatory, Charlottesville, VA. It was created out of dissatisfaction Look forward to seeing everyone at the FORML with available programming toots, especially for obser- Conference and the FIG Convention. vatory automation.

Mr. Moore and several associates formed FORTH, Roy Martens Inc. in 1973 for the purpose of licensing and support of the FORTH Operating System and Programming Lan- guage, and to supply application programming to meet customers’ unique requirements.

The Forth Interest Group is centered in Northern California, although our membership of 2,000 is world- wide. It was formed in 1978 by FORTH programmers to encourage use of the language by the interchange of ideas through seminars and publications.

Page 95 FORTH DIMENSIONS II/4 guaranteed worst case performance of BALANCED TREE far less than a millisecond even in DELETION IN FASL fairly large (over five hundred node) trees.

Douglas H. Currie, Jr. In FUNCTIONAL* systems, FASL trees Nashua, NH are used in a line editor, data stor- age directories, FACT (a truth table compiler), message routing tables, Abstract microcomputer assemblers, as well as the FASL dictionary. A general pur- FAS L ( Func t iona 1 Automat ion pose microassembler uses a balanced Systems Language) is a derivative of tree (fields) of balanced trees (con- FORTH containing significant modifi- tents) to describe the target micro- cations. This paper discusses one of instruction. The use of multiple these, the FASL tree, an implementa- trees allows identical keys in tion of the AVL (height balanced) different contexts (e.g., label names tree. FASL trees are a data type of and macro names). the language, and are used in the implementation of the dictionary. An The height-balanced tree was first algorithm for deletion in FASL trees proposed by two Russian mathemati- is presented, as well as a FASL cians, G. M. Adel'son-Vel'skiy and E. program to implement the algorithm. M. Landis in 1962 (hence -AVL tree). The idea is to maintain a binary tree Kev Words and Phrases so that the height of the subtrees at any node differ by at most one. The deletion, height-balanced trees, technique incurs a penalty of only binary trees, search trees, FORTH. two extra bits per node (FASL uses an 8-bit byte), and makes it possible to CR Categories search for, insert, or delete a node with a worst case of O(1og N) opera- 3.7, 4.10, 4.20, 4.34, 5.25, 5.31 tions (where N is the number of nodes). Introduction to Height-Balanced Trees Introduction to FASL Trees The use of balanced trees has become almost commonplace in data Algorithms for search and inser- base management, and is seeing limited tion in AVL trees are presented by use in symbol tables. Many systems Knuth (The Art of Computer Program- would benefit from the use of balanced ming, Vol. 3, Section 6.2.3); these trees, but their designers could not two algorithms were implemented in afford the time to develop the algo- machine code and (along with Indirect rithms. A case in point is the Threaded Code) became the basis for extensive use of hashing in "high- PASL. The deletion algorithm was not speed" microcomputer assemblers. . implemented at this time for two Hashing techniques have significantly primary reasons: Knuth didn't give improved the performance of many it, FASL didn't "need" it. Deletions assemblers, but analysis of these occur much more rarely than inser- routines shows a best case perfor- tions or searches; FASL lived for mance on the order of several milli- over a year with no delete operation. seconds (due to the inefficiency of division, or pseudo-random number *Functional Automation Could Inc. generation on microprocessors). FASL 3 Graham Drive trees, on the other hand, have a Nashua, NH 03060

FORTH DIMENSIONS 11/4 Page 96 For example, when a file was deleted balance factor is always minus one, from a FASL directory, the entire zero, or plus one. directory was reconstructed without the "deleted" node. The time penalty incurred was not significant because directories are small (for FASL trees), and had to be copied anyway to be sent to the disk. (FASL lives I- *€ID in a message enviroment. The disk is :onmi in another Cyblok*).

After an overview of FASL trees and their use, the remainder of this paper will deal with the development of a FASL tree deletion pragram in FASL. For an introduction to binary search trees, see Knuth (The Art of , Vol. 3).

I' I FASL trees are composed of a number of sixteen byte nodes (see Figure 1). The tree is identified with the address of its head node. From the head node we may find the root node, and thus the entire tree. The head node contains a pointer to its root node, a pointer to its available nodes list, and an integer which is the ':Cult 1 tree ' s he igh t .

All nodes other than the head node contain an eight byte key, a left The insertion routine obtains new link, a right link, a one byte balance nodes from the free nodes list. This factor, and three uncommitted bytes. list is simply a number of nodes The key is used to access the node. linked with their right links. A Given a key, the search routine null right link indicates the end of compares it to the key at the root the free nodes list. When the inser- node. If it is less, the search tion routine needs a free node, it continues with the node identified obtains its address from the free (pointed to) by the left link. If it nodes list pointer in the head node, is greater, the search continues with and replaces it with the right link the node identified by the right link. of that node. If the free nodes list The search terminates when it matches pointer is null, then the tree is the key (success), or reaches a null full. link (failure). The null link is represented by zero. The balance The technique used by the insertion factor is the height of the right routine to maintain tree balance is subtree minus the height of the left essentially the same as for deletion. subtree. The insertion routine always Basically, four cases arise in inser- leaves the tree balanced, i.e., the tion when the tree must be rebalanced: single or double rotation, left or "Cyblok is a registered trademark of right. The discussion is postponed Functional Automation/Gould Inc. until the section on deletion.

Page 97 FORTH DIMENSIONS 1114 To get a feeling for the efficiency Later, the data may be retrieved of FASL trees, consider a dictionary onto the stack as follows: of five hundred nodes. If this dic- tionary was stored as a linked list, PAD SYMBOLS FIND a worst case access time of five hun- IF F#@ dred compares would be incurred, with ELSE FAIL FAIL FI an average access time of two hundred fifty compares. Stored as a FASL If the string in PAD is the same as tree, this dictionary has a worst case was used in the preceding example to access time of nine compares, an insert the node, then the data re- average of eight. The numbers become trieved will be 12 3456. If another even more convincing as the dictionary string is in PAD, then the data grows in size. retrieved will be 00 0000, unless a node has been inserted with this FASL Tree ODerations string as a key, in which case the data associated with this node will FASL provides operations for cre- be retrieved. ating trees, inserting and searching for nodes, and accessing the uncom- From the example, it should be mitted data in a node. For example, clear how to use the FASL trees for a the FASL text symbol table for an assembler. Text is read to PAD until a delimiter, and 100 TREE SYMBOLS then inserted in the tree. In the case of labels, the node would be creates a tree named SYMBOLS wlth two initialized with the current pseudoPC, hundred fifty-six available nodes (the and a flag byte to indicate "label." radix is hexadecimal). Assuming there If the inserted text was a macro name, is a string of text in an area named the node might be initialized with a PAD which is to be used as a key to pointer to the macro text and a flag access the tree, byte to indicate "macro. '' Alterna- tively, separate trees may be created PAD SYMBOLS LEAF s3 that identical keys may be used as macro and label names. Later, when a inserts a node in the tree SYMBOLS label .or macro is used, it may be with this key. LEAF leaves a boolean looked up in the tree to find its flag on the stack to indicate success corresponding values. or failure, and if successful leaves the address of the new node on the The TREE operation allocates space stack under the boolean. for the tree in the FASL Global Area (where code for colon-words is Usually, new nodes are initialized placed). Another operation, TREEINIT, with some data. The following FASL is provided to initialize trees in text will insert a node with the key space that the FASL user has allocated in PAD (as above), and initialize its (e.g., in FUNCTIONAL Cybloks there is uncommitted bytes with constants: a minimum of 256K bytes of "Public Memory" which is accessed through 12 3456 PAD SYMBOLS LEAF 'Windows," and is not part of the FASL IF F#! Global Area). The TREEINIT operation ELSE DROP2 FI is often used in the Local Area (space allocated on the Return Stack) or in Public Memory.

FORTH DIMENSIONS 1I/4 Page 98 The Deletion Algorithm for FASL Trees This path begins at the head, and ends in cases one and two with the A deletion algorithm for binary node which re- placed X (i.e., the trees, and the steps required to adapt node which is pointed to by the link this algorithm to balanced trees are which used to point to X). In cases provided by Knuth (The Art of Computer three and four the path ends with the Programming, Vol. 3, Sections 6.2.2 node which used to be the right son and 6.2.3). The details of the bal- of the symmetric successor of X. anced tree deletion algorithm are (Note that the ending node may actu- presented here, but first a review of ally be null.) binary tree deletion. I :CURi I TREE DELETE OLI - *I. --_._ Deleting a node from a binary tree may be decomposed into four cases (see Figure 2). Call this node "X". In the first two cases one of the links of X is null, the other link is a "don't care" (i.e., a pointer or null). In both cases the other link simply replaces the link pointing to X. In case three the right son of X has a null left link. In this case the left link of X replaces the left link of its right son, and the right link of X replaces the link pointing to X. In case four the symmetric successor of X must be found. This is done by following left links starting with the right son of X until a null link is encountered. The left link of the father of the symmetric SGC- cessor is replaced by the right link of the symmetric successor. The left and right links of the symmetric successor are replaced by the respec- tive links of X, and the link which points to X is replaced by a pointer The path may be represented as a to the symmetric successor. list of pairs

In all cases the essential left- to-right order of the nodes is pre- served. The deleted node is inserted in the free nodes list, and the algo- where each N. j is a node address, and rithm terminates. each f.j is a direction (-1 left, +1 right). N.0 is the head node, f.0 is All that is required ( !) to adapt the +1 (since the "right link" of the this algorithm to balanced trees is head node points to the root). The to insure that the balance is main- pair (N.i , f.i) is the end node minus tained after the deletion. An impor- one, and identifies the end node of tant observation is that the effect the path (which, again, may be null). of deletion on the binary tree is to Rebalancing may be required at each reduce the length of a single path node in the path, starting with node through the tree by one. (N.i , f.i), working backwards. This is in contrast to insertion where re- balancing is required for, at most, one node.

Page 99 FORTH DIMENSIONS II/4 Adapting the deletion algorithm (5) There are four cases: for binary trees to balanced trees requires that as the tree is searched Link(1 , X) = 0 ; for the node to be deleted (and for Top(N.k , f.k). its symmetric successor in cases three Set Link(f.k , N.k) to and four), a list of pairs describing Link(-1 , X). the path is created. Once the node Go to (7) to rebalance. is deleted, nodes are rebalanced back along the path until a termination Link(-1 , X) = 0 ; condition is reached.. Top(N.k , f.k). Set Link(f.k , N.k) to The path is constructed on an Link(1 , X). auxi 1iary stack. The operations Go to (7) to rebalance. "Push(x,y)" to push a pair, "Pop(x,y)" to pop a pair, and "Top(x,y)" to read Link(-1 , Link(1 , X)) = 0 ; the top pair without popping are used, Top(N.k , f.k). as well as the capability of saving Set Link(-1 , Link(1 , X)) and restoring the path stack pointer. to Link(-1 , X) . Set Link(f.k , N.k) to Using the notation "Link(-1 , M)" Link(1 , X). for left link of node M, "Link(1 , M)" Set Bal(Link(1 , X)) to for right link of node M, "Bal(M)" Bal(X). for the balance factor of node M, and Go to (7) to rebalance. "Key(M)" for the key of node M, the following is a detailed algorithm for Otherwise ; Push(X , l), set deleting the node with key K in a 2 to Link(1 , X). balanced tree. Save path stack pointer in PSP. (1) Initialize local path stack. Go to (6) to find symmetric Push(HEAD , +1). successor. Set X to Link(+l , HEAD). (6) Push (2 , -1). (2) If K is less than Key(X), go to Set Z to Link(-1 , 2). (3) moving left. Re peat this step until If K is greater than Key(X), go Link(-1 , Z) = 0. to (4) moving right. Finally, Top(N.k , f.k). Otherwise go to (5), key is Set Link(-1 , N.k) to found . Link(1 , Z). Set Link(-1 , Z) to Link(-1 , X). (3) If Link(-1 , X) is 0, go to Set Link( 1 , Z) to Link( 1 , X) . (ll), key is not in tree. Now swap PSP and the path stack Otherwise Push (X , -l), set X pointer. to Link(-1 , X), and go to (2), Pop(N.k , f-k) , keep searching. Top(N.k , f-k), Push(Z , l), substitut ing the symmetric (4) If Link(1 , X) is 0, go to (11) successor for the deleted node key is not in tree. on the path stack. Otherwise Push(X , 1), set X to Swap PSP and the path stack Link(1 , X), and go to (Z), keep pointer again to restore. searching. Set Link(f.k , N.k) to Z. Set Bal(Z) to Bal(X). Go to (7) to rebalance.

FORTH DIMENSIONS II/4 Page LOO (7) Insert X into the free nodes -Bal(X) and Bal(B) to 0. list. Otherwise set Bel(A) to 0 and Bal(B) to -Bal(X). The algorithm proceeds as follows Set Bal(X) to 0. beginning with the last pair of the (double rotation) - path: Set Link(-f.k , A) to Link(f.k , X). (8) Pop(N.k , f.k). Set Link(f.k , X) to A. If N.k = HEAD, set Height(HEAD) Set Link(-f.k , B) to to Height (HEAD)- 1 decreasing the Link(-f.k , X). height of the tree, and go to Set Link(-f.k , X) to B. (11) terminating the algorithm. Top(N.k , f.k), set Link(f.k Otherwise go to (9). , N.k) to X. Go to (8) taking one more (9) There are three cases based on step back along the path. the balance factor:

(9a) Bal(N.k) = 0 ; Set Bal(N.k) to -f.k, and go to (11) terminating the algorithm. FlGUAE 1 IlEBALANCE (9b) Bal(N.k) = f.k ; Set CASE I (TWO SITU4TIONS - REFLECT DIAGRAM LEFl/EIGltl) Bal(N.k) to 0, and go to (8) taking one more step back along the path.

(9c) Bal(N.k) = -f.k ; Rebalancing is required, go to (10).

(10) There are again three cases. (Referring to Figures 3, 4, and 5, A is N.k, a is the subtree containing the path the algorithm has been following, B is the node pointed to by the opposite link from the link which points to a, Link(-f.k , N.k)):

Bal(A) = Bal(B) (Figure 3); Set Bal(A) and Bal(B) to 0. (single rotation) - Set Link(-f.k , A) to Link(f.k , B). Set Link(f.k , B) to A. Top(N.k , f.k), set Link(f.k YEW BALANCE 1 , N.k) to B. A C B 0 Go to (8) taking one more step back along the path. NEW SUIROOT 9 KEEP FIXIYG.. . Bal(A) = -Bal(B) (Figure 4); If Bal(X) Bal(A), then set Bal(A) to

Page 101 FORTH DIMENSIONS I1/4 1

(1Oc) Bal(B) = 0 (Figure 5); Set Bal(B) to -Bal(A). (single rotation) - Set Link(-f.k , A) to Link(f.k , B). Set Link(f.k , B) to A. Top(N.k , f.k), set Link(f.k , N.k) to B. Go to (11) terminating the algorithm.

(11) Deallocate path stack. Done!

FlCUaE 4 -REBALANCE CASE II (TWO SITUATIONS - REFLECT DIAGRM LEFT/RIM) 3LJ - 1.EU ----

Implementing the Algorithm in FASL

A FASL program to implement the balanced tree deletion algorithm is relatively straightforward (see the listing below). Some preliminary colon-words are defined to access the links, and to access a Local Stack. RCRUHB and LCRUMB are defined (in commemoration of Hansel and Gretel) for adding pairs to the path stack; OLD: - then colon words for the three cases NEW: ---- encountered in rebalancing are defined.

The main colon-word, DROPLEAF, takes stringname and treename par- ameters just like LEAF and FIND, but leaves no return values since it is always successful. The PROC... ENDPROC pair allocate and deallocate a Local Data Area for the path stack and associated variables. For the most part, DROPLEAF follows the

FORTH DIMENSIONS II/4 Page 102 deletion algorithm presented. Nested : ROTCASEI FAIL OVER C! FAIL OVER2 C! IF statements are used to evaluate SlNCLROT SUAPDROP FAIL NAP ; the case constructs. The string : ROfWE3 OVER C@ NEG OVER C! compare in the first (search) WHILE SINCLROT ; loop tests for less-than directly, : ROTCASLZ OVERZ OVERZ OVER2 OVEU - 3 + @ and examines FASL Registers (WO, Wl) SIWCLROT SYAP NEG sum OVEW SWAP to resolve the trichotomy. (This is SINCLROT SWAPDROP an efficiency measure, and has to do OVER2 Ce OVER Ce - IF DUP C@ NEG SROT C! FAIL SROT C! with the fact that there is not guar- ELSE FAIL SROT C! DUP C@ NEG SROT C! TI anteed to be a string delimiter in FAIL OVER C! SUAPDROP FAIL SWAP; the node's key. ) : IUVEZR + DLJP 6 'I, ! e ;

Empirical tests show that DROPLEAF ( 2.c ) ( <.ME&> ) runs in the SO to 100 millisecond : DROPLW range for trees with about 30 PPOC 500 8 'D 4 'D ! nodes. For comparison, LEAF runs in SWAP OVER the 0.1 to 1 millisecond range on the RCRW 4 MlVEUP same trees. The large difference be- WEILE DUP tween these runtimes results from the IF OVER OVER 8 + SLT? DW IF Onr 10 + K) @ - fact that LEAF is highly optimized ELSE Wl @ 1 - C@ PI machine code, only requires one rota- ELSE FAIL FAIL FI CONTINUE tion maximum, and does not require a IF LCRW 2 ELSE RCRm 4 FI path stack. As previously mentioned, IIOVEUR DROPLEAF is used very infrequently, WILLND DROP and there has been no incentive to SWAPDROP implement it in machine code. DUP IF DIP UNKe IF DUP LLNKe IF DUP DUP LLNK@ IF 1. 'D e 2 'D ! Ram ( E.EIGET BALANCED ) MIP WPUT LCRm SWA?DROP DUP ( TEE DELE= ) LLNR? DUP LLNH! Zl ( 17Ur80 ) mIL OVEIU LLwI(@ OVLR LLW! ( LOW DATA rrRu ) DUP UNXe OVERZ LLNK! ( OFFSET ) OVElK UNK@ OVER XLW! SWAPDROP ( 1 DUPZ'De: ( 2 aaved path mtack pointer ELSE OVER LLNKe OVLR LuII(! 4 path stack pointer RQulQ 6 addrema of link to node LO be deleted. FI 8 start of path 6tack oVl!Rdwn.C! ELSE DUP UJnre I1 ELSE DUP LLNKe TI e*~e! 30 end of path crack + 1 OVER OA + e ovu am!OVER OA + ! ) REPEAT POP ?oP mR2 mL1 SUM - IF DUP DUP ( 1,l ) d : LLNK@ 2 + @ ; IF OVZU + 011 *ID : uNKe 4 + e ; IF 3 + OVER + @ DUP C@ IF ARD ( 2,o 1 ovmz m men d - :LLm!Z+!; IF BOTCASU :aLNK!4+!; ELse m~tiFI ELSE ROTCASE3 PI POP POP DUP ?USU NAP DUP ?USU - 5 + ! ELSE FAIL SWAP C! DROP FAIL FI ELSE DROP C! SUCmI! ( 0,1 ) FI : POP OF?= I 'D +! 4 'D C Ci ; ELSE 2 + +! SUCCEED PI mxL ( 1.1 1 : RCRW DIP PUSH OFFFF PL'SR ; rise DROP ?I : LCRW DUP PUSH SUCCEED PUSH : DROP ENDPPOC ( 3,2 1 : SINGLROT OVER2 LTZ? ;S IF DUP U"K@OnR2 LL"K! SWAP OVER RLNK! ELSE DW LLNXe OVEU ULNK! SWAP OVER LLNK! F1 ;

Page 103 FORTX DIMENSIONS II/4 (1) The names used in the comments correspond to those used in Knuth's Algorithm 6.2.3A.

(2) The routines use variables HEAD and AVAIL to identify the tree and free nodes list on each invocation; the key should be in the eight byte area K.

(3) The variable VTV may be initial- ized to point to the default FASL Credits subroutine DEFNOT which causes a "failure" return on an insertion FASL arose in response to a need attempt to a full tree, or to a within FUNCTIONAL for a simple and user supplied subroutine which efficient interpreter for system allocates a new free nodes list software development. An early FASL (with at least one node) by Manual (1977) was written with placing the address of the list contributions from Eric Frey, Michel in AVAIL. Julien, Roland Silver, and Ron Lebel. The idea of implementing the dictio- (4) Trees are Initialized by placing nary as a height balanced (AVL) tree a starting address in HEAD, an came a year later, and with it the ending address in AVAIL, and FASL TREE data type. calling the routine BTSIUP. On entry, AVAIL-HEAD should be FASL was also made possible by the greater than thirty-two, and unselfishness of G. M. Adel'son- zero mod sixteen. On exit, HEAD Vel'skiy and E. M. Landis, Donald E. will not be modified and will Knuth, and Charles Moore. point to the head node, and AVAIL will point to the free nodes The author has recently learned of list. two language processors which use AVL Trees for symbol tables, but not as a (5) All tree routines are object code data type of the language: a MUMPS relocatable. system (Dave Bridger for Tandem), and the IBM FORTRAN H Compiler. The cur- (6) Quickie symbol table for these rent status of these language systems listings : is not known by the author. BTSIUP El51 tree initial- Special thanks to Kit Andrews for ization typing the manuscript on Functional's FINDIT El 68 tree search Wang Word Processor, and patiently BTSI El 7D tree insertion illustrating the final versions of DEFNOT E6 60 default tree the Figures. overflow sub- routine Assembler Listings for Search and K DO key for search & Insertion insertion, 8 bytes The following pages contain HEAD c2 pointer to tree exerpts from the FASL listings AVAIL c4 pointer to free pertaining to tree search and nodes list insertion for the 6800. Referring to VTV co overflow transfer these listings: vector

FORTH DIMENSIONS II/4 Page 104 55 38b 56 I87 57 388 n 189 117D D1 Q 59 390 1171 DI 0 b0 Orm m: 191 bi ma IYD: 192 1111 Q M bl m0 UULZ (1 0 bJ bb b7 b8 b9 70 71 72 7, 7. 75 1b 1: 77 ma I: 78 OOCI I: 79 moc 9: 80 OM I: i ywa rrcrm 81 mm I: - 82 83 41A Llyl DI 0 ;Q+: 8A 415 LW ra a :?->I 85 blb LW D? 0 M A17 ClY DI U ;Q 87 418 I 619 IIY W CI i -> ? 19 L20 i 1-1m 31, llb Ill? M Q urn: ; s -> I 117 u21 m cc 3ia LIZJ u M 319 U15 I7 05

mu: ; ma u m sxn w A .DD. I25 IlU IA 01 326 UlI 1C m0 117 UY D7 0 YI: 1u I29 U3b D. 0 130 UY )c 0 111 UU lb U 132 131 nY m cc i IICUL m w um 1% IUC bI M

i IT81 m-m

3Y 16s us) br 3bb Ubb LC I61 Ub7 19 3b8 lb9 i -> 370 - 371 ciu DL a 372 11U U M 371 UbC 10 M 171 17: nu a M 37b 1110 21 0 I77 178 u72 w a M: m? 179 U7b 8D U IP In UO U7b 22 Yl U7l 16 I7 I11 U7A 39 i -I II az-i Y3 38A U7l U ?7 19. *m imn

5- Qll Db Dl rn PU m 92 510

Page 105 FORTH DIMENSIONS II/4 ...... ru: mIm 8n- ,cwa~?)smO?l

51) 51% u15 D? u llb 031 I0 10 511 ma 3- Ql9 b? W NIIM 529 U31 ID I1 swI 05 530 Qm 21 0. UA- 511 512 Q3? u m Durm :-1->m 511 Ubl P 02 Lm I 02 ; un ... 531 nu 10 M p. AwJ 131 JY QL5 U 00 Dcxm :1->IQ> 511 ULl U M Lm I M ; IQ) ...

LQ) -> .a) 5% 551 551 PY 11 00 LucauuoI J59 Qll I1 05 bb5 011 05 1M bU PIC b? 00 0 -> w %I QW *? Y7 YI UbI U 00 0 -> KD I -> m 5b1 Pbl bC JM PIL l9 Y5 5u 561 Qb5 D. 0 5UUbl ID 10, =? w 5(1 QU U bb JIO 111 QU Cl W 112 PY 11 bI $11 ; 0 -> KO I15 m ... ; I -> no) llb OLE P 01 LQ) -> ? 11) PIO m a loylM IQ) -> Lo, LDY I 03

0 -> Kv ; 0 -> 8Q) I -> IQ) i -1 -> Kv

;o->Kn ;1->KD ; L(n -7 Ium

i a->w i I(b - a. ODLP

? -> L(b

?uL I!II CUlW 0 -> 14) U.lQUCCZ.0 ms UAm -1 -> Kl> v nar !II ? -> l(b b11 611 Lu. b? 00 NIm 0 -> Kn (16 UY DI U MI 615 U 10 X y. -ax I -> rn

FORTH DIMENSIONS II/4 Page 106 LIZ? 7.1107 CTZ? LT? iL? ea 7 NC' GZ? GTI ADDRGT? SLT?

SZO?

P i addr -- D 1 I n addr - 1 < addr - b 1

f b addr - 1 I n .ddc - I I addrl add12 - 1 I tl- to Y -- 1 ~trawu- J I fra to - 1 I .ddll ddrl - .ear7 f >

I

I addt - D n I I b n addr -- 1 I * - .ddr I

STXI .WIHILITION COmoL w. ln--nnl DUDlICat. COD Ot st.&.~. W...IDD? do: I .nd*l st.st - DM? In-- I Tbiw -my tbp of st.ck. I I -- Lid.. 1 SWAP ( nl nl - nl nl I R*v*rm. top tro stmck it".. OW I nl nl - nl nl nl 1 Make copl of auond It- on top. m. .. .IIx)* +1mpr1 n - 1 0- I nl nZ n3 - nl nZ n3 nl I Mak* copy o! third it" on top. SRQT I nl nl n3 - nl n3 nl 1 Rotmts tbird it- to too. SWIPODOP I nl nl - nl 1 IT... [tt"*l ...?I It: I t 1 DROP1 Inn- 1 -- DMP3 Inn"--] zr.. itr~oi...mc... it.la*l ?I RPOSrn I"-- 1 . ... iLsoS I --"I w...IY.., ltruol ...Loo? stack. udl,. .1t.lS.L.. .UlT 'I I s - mddr I CQPUt. addromm Of nth byte on n return stack. 'S I 1 - addr I Cmpuf. .ddroos Of mth byte on top I I 'S # s OM1. nc?lmr...mIL Untll: I t - I nw.. m LOGICU COFII*ln...Itr"rl... IILPID... 1t.lS.l.. . I *I .2 - *m I cmtinw: I ! - 1 I 11 '2 -- di1f.r.nee I I .I -2 -- product 1 1 sl 12 - quotient 1 I 11 .I -- .Mu10 1 I .1 .2 -- d I I d * -- quat lod I I a1 .1 - gum Dod 1 (.--dl I s - n.qst,On I < a -- Sb.OlUt. 1 I SI sz - .I" I I .l s1- U. I I "1 "1 - I"t.I.rtIOn 1 I "1 "1 -- sonlunctlo" 1 I ul ul -- dllyunctlon 1 I u -- cap1u.nt J \ -11 I -01 SBL (nu-ni sw I""--"l ROL < n Y -- n I ROR I nu-- n 1

Page 107 FORTH DIMENSIONS II/4 the programmer would like to retain the selector value, a simple "VCASE @" directly after CASE will preserve the contents of the stack. Then, for any following Forth words having nested DO-CASE structures, the problem of overwriting is solved. The variable storage method takes a little longer to retrieve the current selector value (i.e. VCASE @ versus DUP, or versus I), but retrieving VCASE has not been very common in my experience. To me VCASE @ is more self-explanatory in the context of the program than either DUP or I. In addition, my feeling is that messing up the return stack so the normal index values (I & J) cannot be used within a CASE. . . END-CASE phrase, is a definite disad- vantage. To solve return stack problems like this, advanced Forth Systems, such as the one now at Kitt Peak or STOIC, have three stacks. The extra stack is used explicitly for LOOP indices while the rturn stack is used for return addresses and tempo- rary storage. In lieu of a third LETTERS stack, the VCASE variable presents a clear way of handling this situation. The variable storage method would I would like to point out a pos- need to be changed to user variable sible misconception that I noticed in storage if multi-tasking was to be one of the judge's comments on page implemented. This is only slightly 54 in the special FD on Case Struc- more complicated than the current tures. The third itemlisted as an version. In my extension, I tried "advantage" states "(The) case both return stack and variable selector is kept on (the) return stack methods. I selected the variable instead of in a special variable. storage due to speed improvements as This allows nesting of CASE con- well as the aguments above. Also, in structs." I'd like to point out that regards to speed, the CALL'S and JMP's the FORTH-85 CASE structure, which within the code statement for CASES uses a variable (VCASE), is also are weak in style snce the objective nestable. The reason for this is that in code statements is speed. These once a match has been made and execu- really should be expanded out (i.e. tion is in progress between, CASE MACRO'd!). My original intent was to . . .END-CASE the contents of VCASE make the article do double duty be have served their purpose. Further demonstrating these techniques as a nesting at this point can alter the stepping stone to some debugging contents of VCASE without problems. methods I came up with. When the unnesting occurs, END-CASE shoots the Forth instruction pointer to the words after the end of the Bob Giles case structure. END-CASE does not Tulsa, OK need the older contents of VCASE. If

FORTH DIMENSIONS II/4 Page 108 THE EXECUTION Three words shown in block 502 listed below are used to change the VARIABLE AND A RRAY: contents of execution variables and arrays.

INSTALL Michael A. McCourt University of Rochester returns the code field address of .

A useful programming construct is IN the jump table or 'COMPUTED GO TO' type of structure. In Forth the exe- stores the code address in the cution variable and array can be used. parameter field of XEQ name. The Forth word EXECUTE executes the code address on the top of the stack.

: XEQ @ EXECUTE; stores the code address at the offset in the OXEQ array. a word containing a code address as its parameter can be created. As an Thus the previous example could be example written as

: TEST ." THIS IS A TEST" CR ; 0 XEQ FRED INSTALL TEST IN FRED 0 XEQ FRED ' TEST CFA ' FRED 2+ ! Note that INSTALL and IN work within The word TEST can now be executed by a colon definition, e.g., typing FRED. You might ask--why not type TEST to execute TEST? The reason : DUMMY ; is that FRED is now a variable--of : TURN.ON INSTALL TEST IN FRED; sorts. By changing the contents of : TURN.OFF INSTALL DUMMY IN FRED; the parameter stored in FRED the action of FRED can be changed. Execu- Execution variables are useful for tion arrays are similar, however, here a variety of functions such as crea- several code addresses can be stored ting forward references, switching and later accessed by index number. output and/or input routines among In our Forth system (an updated URTH several terminals, debug routines and system to Forth-79 running on a of course implementing a jump table. PDP-11) the Forth code address of zero is disallowed and will cause execution Examp 1e s of the current ABORT procedure which itself is contained in a variable, 1. JUMP TABLE i.e. Prob len : : ABORT ABEND @ EXECUTE : Define a function that will per- All execution variables and arrays form one of 26 operations depending are initialized to zero so that they on which control key was typed. will have predictable results. Possible Solution:

26 ()XEQ CTRL-KEY

Page 109 FORTH DIMENSIONS II/4 INSTALL 1FUNCTION 1 0FFSET.TN CTRL.KEY TTO TEST2 ( CONTROL CHARACTERS FOR INSTALL 2FUNCTION 2 0FFSET.IN CTRL.KEY 0 0 TPC HAVE NO EFFECT)

22 LIST ( LISTING SENT TO PRINTER ) TTl ( BACK TO DISPLAY ) INSTALL 26 FUNCTION 26 0FFSET.IN CTRL .KEY 3. FORWARD REFERENCE

: OPERATOR? BEGIN KEY DUP 27 <= At times early in an applicarion IF CTRL.KEY ELSE DROP THEN AGAIN; program one needs to define an error handling routine. However, since none One could implement the above with a of the higher level words have been case or select statement, but the defined the error handling is rather execution array has less overhead in primitive. Execution variables allow execution speed and memory usage. one to 'leave a blank' for the error routine. 2. MULTITERMINAL DRIVERS Suppose one has Problem: 0 XEQ DERROR One has a video terminal with addressable cursor and a 'dumb' hard- copy terminal. The latter terminal : DIO GO.BIT OR DEVICE.CONTROL ! does not accept cursor control charac- WAIT .FOR.DEVICE .DONE ters gracefully. DEVICE.STATUS @ O< IF DERROR THEN ;

Possible Solution: Assume DIO is for control of a mag tape drive. At this point in the One solution which alleviates this application program DERROR would nor- problem is shown listed below in block mally be able to do only an ABORT. 500. (Publ. note: we're not printing With a tape drive one would prefer to block 500.) The word CTRL is an exe- have some sort of recovery procedure cution variable. When the video ter- on write errors to either delete the minal is operating (TT1) all control last file or at least write an End of characters are EMIT'ed; however, when File 'mark. With the execution vari- the printer is installed (TTO) the able one can install such a high level control characters are DROP'ed. routine at a later time after all the necessary words (such as skip record, The words EMIT and KEY are defined read record, and write EOF) have been as state variables as is ABEND (user defined. DERROR could also be defined variables might be a familiar name to as an ()XEQ array and each error would some) and are addressed for multi- have its own associated error hand- tasking. They permit each task access ling. to its own terminal driver. The previous examples demonstrate : TEST2 0 0 TPC ." TESTING" ; the power of the ( POSITION CURSOR AND PRINT ) Forth constructs. XEQ and ()XEQ are just two examples of defining words. It is possible to build a wide range TT1 TEST2 ( 'TESTING' WILL START AT of such defining words from words that POSITION ) build simple linear arrays to ones that define complex relational data bases. In all cases one is associ-

FORTH DIMENSIONS II/4 Page 110 ating a data structure (here, a simple each having 15 satellite processors. code address) with an algorithm for FORTH runs under an RT-11 operating using the data (here, EXECUTE the code s y st em. Inst rume n t a t i on siinu la t ion address) and as Wirth has written (a function generator + noise) is one DATA STRUCTURES + ALGORITHMS = use. PROGRAMS* Bill Ragsdale announced the Asilo- "Wirth, Niklaus, "Algorithms + Data mar FORTH retreat (cf., FD Vol. 11 Structures = Programs," Englewood No. 3 €or details). Cliffs, Prentice-Hall, Inc. 1976. Kim Harris described OPTIMIST, a program which reminded me of a cantankerous ELIZA. This FORTH program, originally written in PL/1 by Kildall, exemplifies a SECURED vocabulary as part of Kim's tutorial on PRIVATE VOCABULARIES. He showed how they are produced, tested and sealed.

Howard Pearlmutter d i scu ssed FIGGRAPH and the "human interface" of FORTH. The FIGGRAPH committee is to generate and articulate hardware specs, goals, and a vocabulary. Howard advised us to attend the HOME BREW COMPUTER CLUB'S showing, via a G.E. LIGHT VALVE, of computer graphics. (I saw it and it was as entertaining as LASERIUM).

Handouts included:

- Harris' OPTIMIST and PRIVATE MEETINGS VOCABULARY support - Zimmer's TERMINAL, a program to teach a FORTHed Ohio Scientific Instruments 0s-650~3to act dumb NORTHERN CALIFORNIA - FORTH MODIFICATION LABOUTORY' s CALL FOR PAPERS: (Programming methodology, Virtual Machine Implementation, Concurrency, Language & Compiler, Applica- Ray Dessey, a chemist from Vir- tions, and Standardization. ginia Polytechnical Institute in Blacksberg, was visiting and he des- cribed his recent trip to China. HELP WANTED FORTH accompanied him embodied in an AIM and students at Futan University, Shanghai, got a taste of FORTH. Dr. SENIOR PROGRAMMER to produce new poly- Dessey said the University already FORTH systems and applications. had 3 LSI-11's with Pertec floppies. Contact: Carol Ritscher He also described Virginia Tech's FORTH, Inc. teachinglresearch machine which is a 2309 Pacific Coast Hwy. network with 3 three terminal hosts Hermosa Beach, CA 90254

-. Page 111 FORTH DIMENSIONS II/4 PROJECT BENCHMARK

l' 51- A small, informal group of micro- 9' ,7- computer enthusiasts here in Albu- querque read with interest "Project Benchmark" in the June issue of the magazine "INTERFACE AGE." We have amongst us a variety of systems and 6:' 11' languages, including 8080, 6800, and 11' the AM-100, interpreter and compiler 51' versions of BASIC, and fig-FORTH on the three system types. We ran the d' !5 benchmark program all around and have :V' attached the results of our testing.

We found the results to be most 11' interesting and offer them to the 81' members of the Forth Interest Group. In addition to the timing results, there was also a significant advan- tage in memory for the FORTH programs. The compiled AlphaBasic program size was 192 bytes while the FORTH bench- mark program size was 166 bytes. All three implementations of FORTH were based on the fig model, and the pro- gram ran without modification on all systems demonstrating the transporta- bility achievable with FORTH. IcIr I1 UIIII L1sl-l - 1 1. I have attached a listing 6f the I S FORTH program. The implementation of b the language for the 8080 and the 6800 7 were from fig, while the Alpha Micro version was provided by Sierra Com- puter Co., Albuquerque, NM.

George 0. Young 111

Albuquerque, NM J . :ucoIDI: . ,

I? 11 (1 -1 111 131 111 13s 111 179 181 191 193 LVl IVV I11 213 211 219 111 23s 1bL 231 lY7 163 2b9 111 111 :s1 31 2v1 A1 111 111 111 131 Ill 161 IS1 139 lbl 111 I19 111 I89 191 601 -09 ilV rll 611 (11 b1V bA1 .-V z51 bbl L61 6bl (19 i(l 691 *v9 SO1 M( I21 511 HELP WANTED 361 SLl jSl Jbl 561 171 111 $11 591 5V9 b01 bO1 611 (11 (19 611 bbl bh1 Ml 6Sl 5s9 661 671 617 681 691 mi 1ov 119 111 711 71) 111 151 151 161 76V 171 781 191 809 811 87.1 821 1121 829 111s 018J7 8SV 663 811 881 883 881 So1 Vll 919 VIV 911 9bi 9b1 951 9b1 $11 (11 981 991 991 i:Ylswu) FORTH PROGRAMMERS (or ASSEMBLY program- mers who want to learn FORTH). Contact: Gary Osumi (714) 453-2345 Hydro Products, San Diego, CA

FORTH DIMENSIONS II/4 Page 112 IPS implies a test following. But with A GERMAN FORTH-DIALECT the preceding test YES? is more appro- priate. Of course these fine points Dr. Karl Meinzer may not be very important. Others are Marbach, W. Germany more so: numbers used an truth- variable on the stack use only the least significant bit. This allows The AMSAT-Phase 111 communication the 16-bit logic operators like AND satellites for radio-amateurs utilize OR or XOR to be used consistently with a computer on board for a variety of truth-variables. tasks. In order to simplify the programming and to allow a simple A major difference is the way names dialogue with the spacecraft the are encoded. I did not like the limi- language IPS was developed (in 1976). tations coming from the 3 characters It is a Forth-derivative geared very plus length codes; but then neither strongly towards engineering applica- did I want to use more than 4 bytes tions (real-time control) and by now for the code. The following technique it is also used in a variety of was adopted: from all characters of control-related areas. The following the name (up to 63), a division lines describe the rationale of the remainder using the polynomial X24 + system and its main differences as X7 + X2 + Xl + 1 is computed (3 bytes) compared to FORTH. and stored with the length of the name. This technique allows abitrary Area of ADDlication names; e.g. , MACHINE-A1 and MACHINE-A2 are distinct and not confused by the The IPS development was aimed in system. particular towards the "low" end of computers. Most control applications Theoretically there is a small (10 do not justify a larger computer for to the -7) probability of a collision cost reasons. On the other hand, --in practice I never yet encountered these applications profit most from a one. In any case, no harm can come powerful language processor since the from this because in IPS the system common techniques are very clumsy to does not allow the redefinition of use. The computer I had in mind when names. This "advantage" of FORTH was I designed IPS was at about the level dropped very early because from our of the TRS-80 with 16K bytes of RAM user-feedback it soon became clear (integral video memory and cassette that it was--directly or indirectly-- for mass storage). For real-world one of the major causes for program- interactions control-I/0 and a 20ms ming errors. interrupt must be added to complete the system. Other plausibility checks were added to make the system more for- The IPS Language giving against the typical program- ming blunders. (I do not believe in An introduction to IPS was given the FORTH-assumption that the pro- in BYTE, Jan. 1979, pp. 146; so here grammer can be perfect--I am a good I want to explain the difference to example to the contrary). In fact, a FORTH. First: for the names I tried few checks can make the system vir- to find words which are more logical tually crashproof. Of course, one has in a postfix environment. Take the to be careful not to get carried away IF ELSE THEN construct, e.g., in IPS with this--if the integrity of the it is replaced by YES? NO: and THEN. system is reduced, much of the power This seemed more logical since the IF of a FORTH-like language goes away.

Page 113 FORTH DIMENSIONS II/4 Three examples within IPS: word at a time before it returns to the chain. This keeps all the * During definitions the colon puts debugging capability of the inter- an unused address on the stack. preter a hand while other tasks are The semicolon checks for this executing. number: if it finds a different number, most likely a structuring The system is augmented by the error has occurred. The defini- concept of “pseudo-interrupts. ’* The tion is removed and an error address interpreter (NEXT) is effec- message is written. tively a stacklnachine which has ideal properties for interrupting it--no * Each word has a unique ?-bit saving is required. If the address identification in the name field interpreter can accept these pseudo- defining its use in the interpre- interrupts between the execution of tive mode. Words like YES?, for code-routines, a very powerful high- example, are not executed outside level interrupt-concept is possible. de f ini t i om-- so no “magic effects “ In IPS such a pseudo-interrupt is exe- can result. cuted every 2Oms to keep the keyboard alive and for timekeeping purposes. - The number of interpreter states Other pseudo-interrupts may be added the programmer has to keep in mind as required. is minimized. The base for number conversions is set explicitly. Signalling to the address inter- Numbers like 40 or -721 are preter the pseudo-interrupt request treated as decimal, 103 or IAF07 without creating additional overhead as hexadecimal numbers. is a bit involved with most pro- cessors. Only with the CDP 1802, Real-Time Multiprogramming this is straightforward--the address interpreter contains a jump that can The typical situation with real- be made conditional on an external time control has the processor waiting signal (External flag). With the for some event, then executing a task other processors a real interrupt is --usually very fast--and then again used to modify the code of NEXT; waiting for other events. In prac- admittedly a less than desirable way tice, typically the computer must of programming. Since this occurs attend to a number of such tasks. only at a single point, it was con- This allows for a fairly simple multi- sidered to be the lesser evil over a programming concept. The tasks are possibly increased duration of NEXT. put in a cyclic “chain,“ an array con- taining the addresses of the tasks to Handling and Testing be executed. The system executed them periodically in a roundrobin fashion. IPS is strongly TV-screen Provided that none of the tasks oriented. This allowed the stack to “grabs“ the processor this results in be continuously visible by putting a a reasonably fair arbitration of pro- display-program into the chain. For cessor time and was found sufficient debugging it is a great help not for most control applications. Two having to request the stack-content, operators are provided to allow but seeing it continuously. During dynamic and static task allocations: the operation of chain-operators the INCHAIN and DECHAIN. system remains “live,“ you always can go after problems and investigate. The interpreter/compiler is also a task in this sense--it executes one

FORTH DIMENSIONS II/4 Page 114 Typically, programs are first the hardware configurations have much written on cassette with the integral more connectlons with the system than text-editor as blocks of 512 bytes say with a BASIC interpreter. Typ- each. Then the blocks are compiled ically we qodify the IPS meta-source and tested. If necessary, blocks may to match the hardware at hand and then be edited on the cassette and recom- run the scurce tllrough a meta-compiler piled to solve bugs. Eventually a producing the new system. The lack of binary dump of the whole program (IPS suitable "sLand.ird-computers" having plus application) is produced to the required rt1'il-t fme hardware exten- facilitate fast reloading. sions so h*s prevented a very widespread distribution qf IPS. NO^ Experiences So Far we have a version running on the TRS-80 with 'i few restrictions; by Primarily, the system was adding some hardware these restrfc- developed for the Phase I11 space- :ions go away. As next step we craft that was launched in May 1980. iritend to build s meta-compiler run- It gave the handling of the satellite ~ingon an t:nmodified TRS-80. Hope- an unprecedented degree of flexibility fully thiq WPY we can get "out of the and at the same time helped to solve cvcle" and t\,us tsnablr J widespread the rather complex attitude control distribution of IPS. The large number problems with a minimum of pain. The of letters I received after the BYTE spherical trigonometry of the satel- paper convinced me that the need for lite was solved very elegantly by such a system is very real. I should Cordic-type rotation operators rather be pleased if this letter also pre- than the conventional solution using senLs a stimulu:; to FORTH programmers sines and cosines. This allows d to add some of the IPS concepts to geometrical analysis of the problems enhance its usefulness for real-time rather than the much more complicated centrol . alebraic analysis.

Unfortunately the launcher (ARIWE L02) failed and the spacecraft bas destroyed--a repeat is scheduled for AUTHORS WANTED early 1982. The ground equipmecr also uses IPS. An English version for the 8080 using an S-100 bus computer was Nountain View Press, the source used for the safety surveillance for printed FQRTH, will publish, computer. advertise dnd distribute your FORTH in printed form. Subscantial royalty Furthermore, a large nurober of arrangement. COSMAC based computers within the University of Marburg utilize IPS for Contact: Roy Martens a number of research-data-acquisition Mountain View Press tasks. All in all, OUI' experience PO Box 4656 with the system has fully met our Mt. View, CA 94040 goals--to simplify real-time control.

The Problem of Distribution HELP WANTED !'KO J ECT FI.1 N.1C I.: R to superv i s e a pp 1 i ca - W i h the rea 1 t ime capa bi1 t Y t - i ie riuns and s:)ecis? systems projects. of IPS, portability of the system is Contact: Carol Rirscher much more difficult to achieve than FORTH, Inc . with mote common language processors-- 2309 Pacific Coast Hwy. Hermosa Beach, CA 90254

Page 115 FORTH DIMENSIONS II/4 actions which are executed if the THE CASE, SEL, condition is satisfied. Only the AND COND STRUCTURES: first clause whose condition is met is executed in a given execution of Peter H. Helmets the structure. The integer on the top University of Rochester of the parameter stack is destroyed after execution. The TEST-COND definition shown in figure 1 is an The following is a description of example of the syntax of this the three "case-like'' structures which structure. have been added to URTH for the Lltrasound Lab in the Department of The SEL structure is similar to Radiology at the University of the COND structure except that it uses Rochester. These three structures an implicit test for equality to an were evolved from a simpler prototype explicitly specified integer value. CASE statement developed by Rich Thus when the top of the parameter Harisa at the University's Towne House stack value matches that used within Computer Center and by Larry Forsley the SEL clause, the associated action at the University's Laboratory for is taken. As with the COND statement, Laser Energetics. only the first clause selected will be executed in a single pass through Execution Time ODeration the structure. Additionally, the integer value tested is removed from The three structures to be des- the top of the stack after execution. cribed are the CASE, SEL and COND An example of this structure is the statements. Referring to the examples TEST-SEL definition shown in figure 1. given in figure 1, it can be seen that each of these structure types consists The CASE structure is in turn of a series of one or more clauses similar to the SEL structure except delimited by the << and >> words, and that it uses both an impliclit test enclosed within the appropriate struc- for -equality, and an implicit number- ture defining words: ing of the case clauses, starting with 1 for the first clause. Thus an CASE ... ENDCASE explicit test value does not have to SEL ... ENDSEL be specified. In operation, for or, COND . .. ENDCOND example, a value of three on the top of the parameter stack would cause Each can have an optional OTHERWISE execution of the third clause in a clause which is executed if none of CASE statement, if it exists. Note the other clauses is executed. that the CASE value on the top of the parameter stack is dropped after each These structure types differ in pass through the structure. how a given clause is selected for execution; thus the description of Compiler Operation each type which follows will try to elucidate their difference. The words <<, WHEN, and >> are used in common by all three types of The COND structure is a more structures; thus these words' com- readable syntax for a series of piling operations are dependent on the nested IF.. .ELSE.. .THEN statements. type of structure being used. This The COND structure consists of a "type" information is determined by series of clauses with explicitly the integer on the top of the para- specified conditions and associated meter stack at compile time--which is

FORTH DIMENSIONS 11/4 Page 116 set in turn by the words: CASE, SEL, ( snumEXAMPLES - P~IH- 8 22 80 or COND. These structure defining : FIRST ; : SIC0 ; words each put two integer values on : THIRD ; the stack. The next to top of the : ~O-UIOVS? ; : om! ; stack value is a flag value of zero : IRC-TEIRTI-THBCE ; : FIVE ; which is used by the structure termi- : LEss-TiuN-NEc-Tw ; nating words (ENDSEL, etc.) when they : CWTER-l"+INE ; link up branch addresses. The top of ( SIUTCIWBG TESTS - CON'T - PMI - 8 22 80 ) stack value reflects the type of : TEST-CASE CASE structure being used as summarized << FIRST >> here: << SECOND >> << TEIBD >> OTHliRSYISI WHO-KNous? -2 COND structure ENDCASE ; -1 SEL structure : TEST-SLL ->O CASE structure; this integer SEL << 1 mtm on >> is actually the value of << -33 WEN NSG-THIRTY-TRIIEE >> CASE << 5 WEN FIW >> the previous clause OTEERSYISE v11O-MMIvs? which was compiled. ENDSEL : : TEST-COND The <<, WHEN, and >> words thus COND << -2 < WEN LESS-l"-NEC-TUJ >> analyze the top of stack value to << 2 >- UlIEN GREATER-TtuN-ONE >> determine what words are to be com- OTEERWISE CR piled into the new word's parameter EUDWND list. For example, WHEN for a SEL PICUBE 1 structure compiles the words OVER = and IF into the new word's definition.

The examples of the structures in figure 1 illustrate their respective 2 4 syntaxes. Figures through are OK DtWG TEST-SEL outputs from a FORTH debugger (da- TEST-SEL LINKED TO 3213 : DEFINITION compiler) which emphasize the dif- 3320 07D4 1 ferent compilations of <<, WHEN, and 3321 142C OVER 1 3331 17BE - )----- WEN >> for each type of structure. (Note 3333 07FD $IF 33313 ) that the results of the compilation 3337 327A ONE 3339 0810 $ELSE 3363 ------>> process are listed to the left, while 333D 0111 LIT PFDP the corresponding high level compiler 3341 l42C OVER 1 3343 17BE - )----- WHEN words are at the right.) By studying 3345 07FD $IF 3341 ) the definitions of these structural 3349 3292 NEG-THIRTY-TEBEE 3341 0810 $ELSE 3363 ----- >> words in figure 5 in conjunction with 3343 0111 LIT 0005 33S3 142C OVER ) the examples and the debugger outputs, 3355 17BE - )--- WEN operation should be easily adapted to 3357 07FD $IF 3361 1 335B 392E FIVE other FORTH systems. 335D 0810 $ELSE 3363 ------>> 3361 3261 UMO-KNOWS? OK DEBUG TEST-COND 3363 13BB DROP ------ENDSEL TEST-CONE LINKED TO 3320 3365 0113 $; : DEFINITION OK 3376 1439 3"p ------<< FIGUsE 3 3378 0111 LIT FIFE -- 337C 17DB <

337E 07FD $IF 3388 I------WN 3382 3217 LESS-TtuN-NEGryO 3384 0810 $ELSE 339A ------>> 3388 1439 ~UP_-_-I----_-_ << 338A 1361 2 338C 1806 >-

338E 07FD $IF 3398 I------WEN 3392 32CF GREATER-THAN-ONE 3394 0810 $ELSE 339A --I--->> 339B lA6B CB 339A 13BB DROP ------I------ENDCOND 339c 01c8 $; OK FIGL'RE 2

?zge 117 FORTH DIMENSIONS II/4 OK DEBUG TEST-CASE ZST-CASE LINE3 TO 32D2 MEETINGS : DEFINITION 32E3 0111 LIT 0001 ) NORTHERN CALIFORNIA 3287 112C OVER ) 32b 17BE - )--- << 32EB 07FD $IF 32115 ) 9/27/80 32EF 3242 FIRST 3211 0810 SELSE 331B ------>> 3215 0111 LIT OOO2 ) Dave Lion announced availablility 32F9 142C OVER ) 32F8 17BE - )--- << of his 6800 assembler in FORTH occu- 32FD 07FD $IF 3307 ) pying 1.5 Kbytes of 4 screens. 3301 3250 SECOND

3303 0810 $ELSE 331B --I--->> 3307 G111 LIT 0003 ) Tom Zimmer annonced availability 330B 142C OVER ) 330D 17BE - )--- << of his Tiny Pascal in FORTH; Ragsdale 330F 07FD $IF 3319 again lauded Tom's effort as a bench- 3313 32SD THIRD 3315 0810 $ELSE 3318 ------>> mark (cf ., MEETING REPORT, FD vol. 11 3319 326P VHO-KNOWS? No. 3, p. 59). 331B 1388 DROP ------ENDCASE 3310 OlcB $; OK Martin Schaaf announced committee FIGURE 4 formation for specifying a FORTH machine's hardware.

Henry Laxen of ORTHOCODE Corp. made FORTH CONTROL STRUCTURES ) BASE @ HEX freely available a FORTH "WORDSTAR"- !CADR UPAIun - , ; styled Editor and announced sale of NOT IF 0 ELSE 1 THEN ; GOING FORTH, the tutorial package on WILE ItJliUt ; IW WILE 8" disk by CREATIVE SOLUTIONS. PEPFOBn ' WP !CUR '

EMDWILE~~ UltZ SUM ! ' B> !CUR computer project, gave an in-depth ' NOT !WR ' SIF !WR , ; description of his job. A philosophy IW ENDWILE BASE! :S of team organization and control was graphed and an iterative planning ( FORTH CONTROL STBOCNBES ) BASE @ NEX strategy delineated. Some problems : UNTIL ; IW UNTIL encountered and solved by this manage- : CASEOO; IMPCASE : SEL 0 -1 ; IW SEL ment strategy included: : COW 0 -2 ; IW COND ( DO CONDITIONAL BRANCH ) : >> ' $ELSE !CUR 0 , €ERE - wheel-reinvention, duplication and SWAP ! HERE 2 - SWAP ; IW >> : ENDSEL DROP ( CASE#/FUG ) redundancy prevent ion nERE - tool development (much effort was WILE OVER PEBWRH DUP ROT ! ENDWILE spent on tracers, patches, simu- ZDROP ' DROP !CUR ; lators, target compiler, break- : ENDCASE ENDSEL ; : ENLKOND SEL : IW ENDSEL IMP ENDCASE XI-@ ENDCOND points and documentation and its BSE I :S maintenance) - style adherence (readability and ( FORTH CONTROL STRUCTURES ) BASE @ HEX maintainability) in development : WHEN DUP -2 - and documentation IF ' OVER !CADR - programming environment (which, in ' - !CADR THEN FORTH, is relatively worse due to ' SIP !CUR newness and inexperience)--here BERE 0 , ; : << DUP O< IF the solution entails the project DUP -2 = IF ' DUP !CUR THEN ( COHO ) ELSE ' LIT !CADR 1+ DLTP , WEEN THEN ; manager's close involvement and IW << II4P UHEN intense team interaction : OltIERUISE ; IW OWRWISE BASE ! ;S - accountability of time spent at each level of the plan FIGURE 5

FORTH DIMENSIONS II /4 Page 118 San Diego Thursdays FIG Meeting, 12:00 How to form a FIG Chapter: noon. Call Guy Kelly at (714) 268-3100 1. You decide on a time and place x 4784 for site. for the first meeting in your area. (Allow about 8 weeks for Seattle steps 2 and 3.) Various times Contact Chuck Pliske or Dwight Vandenburg 2. Send to FIG in San Carlos, CA at (206) 542-8370. a meeting announcement on one side of 8-1/2 x 11 paper (one Potomac copy is enough). Also send Various times Contact Paul van der list of ZIP numbers that you Eijk at (703) 354-7443 want mailed to (use first three or Joel Shprentz at digits if it works for you). (703) 437-9218.

3. FIG will print, address and Te xa s mail to members with the ZIP'S Various times Contact Jeff Lewis at you want from San Carlos, CA. (713) 729-3320 or John Earls at (214) 661-2928 4. When you've had your first or Dwayne Gustaus at meeting with 5 or more atten- (817) 387-6976. John dees then FIG will provide you Hastings (512) 835-1918 with names in your area. You have to tell us when you have Arizona 5 or more. Various times Contact Dick Wilson at (602) 277-6611 x 3257. Northern California 4th Saturday FIG Monthly Meeting, Oregon 1:00 p.m., at Liberty Various times Contact Ed Krammerer House Department Store, at (503) 644-2688. Hayward, CA. FORML Workshop at 1O:OO a.m. New York Various times Contact Tom Jung at Southern California (212) 746-4062. 4th Saturday FIG Meeting, 11:OO a.m. A11s tate Savings, 8800 Detroit So. Sepulveda, L.A. Various times Contact Dean Vieau at Call Phillip Wass, (313) 493-5105. (213) 649-1428. Japan F IGGRAPH Various times Contact Mr. Okada, 11115/80 FORTH for computer President, ASR Corp. 12/13/80 graphics. 2:OO p.m. Int'l, 3-15-8, Nishi- at Stanford Medical Shimbashi Manato-ku, School, #M-112 at Palo Tokyo, Japan. Alto, CA.

Massachusetts Publishers Note: 3rd Wednesday MMSFORTH Users Group, 7:OO p.m., Cochituate, Please send notes (and reports) MA. Call Dick Miller about your meetings. at (617) 653-6136 for site.

Page 119 FORTH DIMENSIONS 11/4 FORTH UlrnEflSlOllS

FORTH INTIRISTOROUP Volume II 9.0.Box 1105 Number 5 San Carlos, CA 94070 Price 52.00

Historical Perspective Publisher’s Column Editor’s Column

121 A New Syntax

129 Input Number Word Set

132 1 Structured Programming

133 - 447 Conference Report Letters Meeting Reports New Products

148 Separated Heads

151 FORTH In Print Published by Forth Interest Group EDITOR'S COLUMN

Volume II No. 5 January/February 1981 Alan Taylor. in his speech at the FORTH Convention banquet, pointed out that FORTH is an incredibly Publisher Roy C. Martens powerful tool, snd not precisely a language. in the traditiowl sci~sc Guest Editor S B Bassett FORTH Wkvha close 10 the "naked machine and yet is as general a:id powerful as many High Level Lan- Editorial Review Board guages This makes FORTH the perfect langiiage for writing compilers or pseudo compilers for other Bill Ragsdale !anyuages Dave Boulton Kim Harris If we welt? to produce a compiler lor ANSI Standard John James COBOL. for InLtance. COBOL would run on any ma- Dave Kilbridge chine which had FOHTH running-which is easy' Henry Laxen George Maverick A major software house is presently writing an Ada FORTH DIMENSIONS sclicits editorial material. compiler, and expects to have it out in 1983. comments and letters No responsibility is assumed for accuracy of material submitted ALL MATERIAL I an1 uiliirig to Set that a working FORTH compiler PUBLISHED BY THE FORTH INTEREST GROUP IS IN for Ada could be written in half that time-does anyone THE PUBLIC DOMAIN Information in FORTH want to take me UD 311 the bet7 DIMENSIONS may be reproduced with credit given to the author and the Forth Interest Group S. B Bassett Subscription to FORTH DIMENSIONS is free with membership in the Forth Interest Group at $1 2 00 per year ($24 00 Overseas air) For membership. change of address and/or to submit material, the address is PUBLISHER'S COLUMN

Forth Interest Group 1981) retropective FORTH DIMENSIONS has P.O. Box 1105 covpleted a whole year with the new format and a San Carlos, CA 94070 number of people think it gets better with each issue FORTH Interest Group has grown from 647 members on July 1st to over 2,400 thanks to Byte, EE Tlrnes, InfoWorlU. Cornpri'erWorld arid other publications The HISTORICAL PERSPECTIVE FORML Conference and FIG Convention were great succtsses Many new chapters are being formed, how about you forming one? FORTH vendors are increasing FORTH was created by Mr. Charles H. Moore in ainiost as fast as the membership FORTH is being im- 1969 at the National Radio Astronomy C)Dservatory. plemented or' more and more machines and applica- Charlottesville. VA. It was created out of ctissatisfaction tions are beginning !o roll out Its been a great year for with available programming tools, especially for obser- us and we hope for you vatory automation. 1381 perspective FORTH DIMENSIONS will get Mr. Moore and several associates formed FORTH, better. we will have paid guest editors for each issue A Inc. in 1973 for the purpose of licensing and support of number of new publications and other FIG items w~llbe the FORTH Operating System and programming Lan- introduced !see order form) A number of mailings will guage, and to supply application programming :o meet be done to FIG members about products available (if customers' unique requirements. you don't want to receive these mailings, please drop us a note) We'll be doing more publicity to trade maga- The Forth Interest Group is centered in Northern zines and at complrter shows We need more aticles for California. although our membership of 2,400 is world- FORTH DIMENSIONS, send yours in Happy New Year1 wide. It was formed in 1978 by FORTH programmers to encourage use of the language by the interchange of ideas through seminars and publications. Roy Martens

Page 120 FORTH DIMENSIONS II/5 A NEW SYNTAX FOR so that the use can't see or DEFINING DEFINING WORDS control the object code FORTH reduces complexity by requiring William F. Ragsdale the user to write in a direct, simple syntax.

ABSTRACT The espoused benefits are:

The computer language FORTH util- 1. The programmer directly con- izes a syntax that is generally con- trols program flow. Inef f i- text free (i.e., postfix, or reverse ciency should be more apparent Polish). However, deviations from to the programmer. this principle are noted in the syntax for words that themselves define 2. The compiler is simpler, words. This paper presents an altered smaller, and more time form, which improves clarity of efficient. expression, and generalizes the con- struction for compilers which generate 3. Compiler functions may be FORTH systems (meta-FORTH). added by the programmer consistent with those previously in the system. BACKGROUND The arguments against having to Compilation of FORTH programs con- write in this form include: sists of adding to memory a sequence of numerical values (addresses) corre- 1. God created infix notation. sponding to source text (words). This If not so, why did we learn it period is called compile-time. These as children? God doesn't lie values, called compilation addresses, to little children. are later interpreted by the address interpreter (at their run-time). They 2. Languages are created by com- specify actual machine code which is piler writers, not compiler ultimately executed, under control of users. Therefore, let these the address interpreter. brilliant sources have a larger part of the pie (read 1. FORTH source syntax is close headaches for pie). to FORTH object code. For completeness, it should be 2. Traditional computer languages noted that program branching requires require significant processing reference to addresses not at the to convert their syntax to point of compilation. The compiling object code. The syntax con- words of FORTH (DO, UNTIL, IF, etc.) version is specified using use the compile time stack to hold Backus-Naur statements or interim addresses which specify such "rail-road-track" diagrams of branching. The nesting of condition- N. Wirth. als keeps this process simple and efficient, and obiviates the need for 3. The traditional compiler's con- backtracking or looking ahead in the version adds complexity to the source text. compiler, increases complexity and compiler size. It also masks the results from the user

FORTH DIMENSIONS II/5 Page 121 A PROBLEM Each of the above words is quite different in function and execution, Three exceptions to a context free yet they were all defined by : . The expression exist in FORTH as generally user r.iusL analyze the contents of each used and formalized in FORTH-79: definition to determine what type of vord it is (i.e., colon-definition, 1. The word IMMEDIATE sets the compi iiiig-word, code-def iner, or high- precedence flag of the most :evel--dct incr). Becaiise of tticise recent definition in the varied forms, the glossary definition CURRENT vocabulary. Location of : is only partly complete. The of this bit is done via a other vxriations on : must be discov- va r i a b 1e / voca bu lar y pointer ered 3s they occur. pointing backward in memory an unknown amount. If selectioti Creation and use of the above types of the CURRENT vocabulary has is complicated in that the resi~lti~g been altered, the wrong defini- functioiis are dependent on words tion is made immediate. following within and outside (!) each defiriition. As new words are defined 2. Defining words create a dic- by CRFATE and assigned execution code tionary word header, but some by DOES> and ;CODE , the compiling other word backtracks in the function must backtrack by implici& object code to change the pojnters to alter previously geiterclted execution procedure assigned word headers. to each word created. E.g., Added commentary is appropriate for : C-ARRAY CREATE ALLOT DOES> + ; item 2, above. It is a general char- acteristic of FORTH that a word's 10 C-ARRAY DEMO function may be uniquely determined by the contents of its code field. The word DEMO is created by This field points to the actual CREATE as a variable and is machine code which executes for this proximately altered by DOES> word. Common classes of words which to execute with a much dif- are consistent include: variables, ferent role in making a run- constants, vocabularies. time address calculation. This is not the case with defining 3. ; and END-CODE make available words. These words all have the same for use each correctly compiled code field contents as any other definition. This is often colon-definition which indicates that determined from an alterable they execute interpretively until the pointer, sensitive to the concluding ; . But actually the vocabulary specified as intervening DOES> or ;CODE terminates CURRENT. execution and alters the specifica- tion for the execution of the word To display these cases together: being defined. Philosophically, it appears that this is the grossest :www...; form of context sensitivity of any : XXX . . . ; IMMEDIATE language, due to the generality and : YYY . . . ;CODE . . . END-CODE power of the construct. : ZZZ . CREATE . . . DOES> . . . ;

Page 122 FORTH DIMENSIONS II/5 But this power and generality : C-ARRAY CREATE ALLOT contains its own downfall. It DOES> + ; increases the complexity of compre- hension and complexity of compilation. It would be used in the form: When a novice competently begins to use DOES) and ;CODE he has come of 10 C-ARRAY DEMO age in FORTH. to make an array named DEMO with space for 10 bytes. When DEMO THE COAL executes it takes an offset from the stack and returns the sum of the The goal of the proposed new tech- allotted storage base address plus nique is a uniform expression of the offset. source text that may be compiled for resident RAE! execution, resident ROM Using the proposed new meta- execution or target executior? (from a definer BUILDS) the creation of binary image coapiled to disk for c-ARRAY is: later execution). To enable this uniformity, a context free expression DOES> + ; is used. (the run-time part) BUILDS> C-ARRAY ALLOT ; (the compile-time part) THE PROPOSAL And is used: The proposed syntax for defining words uses only the compile time stack 10 C-ARRAY DEMO (or dedicated pointers), generating just as above. object code and word headers linearly ahead. Each word type has a unique It should be noted that the impact defining word so that no later modifi- of the use of BUILDS> is only In cation of a word definition need be defining defining words. Later use made. A meta-defining word is pro- of such defined words would be as posed which makes all defining words. presently conventional. Each defining word is obvious because each, itself, is created by this "meta-definer". THE NEW SYNTAX

This meta-definer is BUILDS> . Here is a summary of the defining This name is an old friend to some, word syntax that appears at the since it was the name of the word application level. Note that these previously used where CREATE is examples are very close to what we specified by FORTH-79. This word commonly use in FORTH-79. still has its old role of building words which themselves build words, : . . . . ; but is used in a more obvious fashion. Define a non-immediate word Here is an example, written in which executes by the FORTH-79 for a word which creates interpretation of sequential singly dimensioned byte arrays: compilation addresses.

FORTH DIMENSIONS II/5 Page 123 NOW . . . . ; When new classes of words are created with their run-time execution Define an immedia'te word which expressed by machine code, their executes by the interpretation defining word is created thusly: of sequential compilation addresses, and will execute CODE> . . . . ENG-CODE when encountered during compilation. Begin the nameless run-time machine code for words to be CREATE defined by .

As in FORTH-79. BUILDS> . . . . ;

n CONSTANT

As in FORTH-79. Define which, when later executed will itself create a VARIABLE word definition. The code after executes after As in FORTH-79. creating the new dictionary header for to aid VOCABULARY parameter storage. The previous run-time code is As in FORTH-79, but each assigned to each word defined vocabulary is created by . immediate.

When the programmer creates new THE METHOD word types, a significantly different syntax is used, as compared to We will follow the method of the FORTH- 7 9 . honey bee. To propagate the colony the bees need a queen bee. An ordi- DOES> . . . . ; nary bee is fed special hormones to become a queen bee. By regulating Begin the nameless run-time this process the colony regulates its high-level code for words to growth. be defined by . Our queen bee will be BUILDS) . BUILDS> . . . . ; It is originally created as a colon definition. Then it is converted into a new type of word that creates words which always create. This form Define which, when later uses parameters to create a dictionary executed will itself create a entry and then passes control to the word definition. The code users code which specifies completion after executes after of the entry. creating the new dictionary header for to aid par- We will break the CREATE DOES> ameter storage. The previous construct into two parts. The creat- run-time code is assigned to ing part will be called BUILDS> with each word created by the right pointer emphasizing that . the following word 'builds' other

Page 124 FORTH DIMENSIONS II/5 words. BUILDS) is the me ta-def ining Some systems achieve the same word since it is the source of all result by selectively linking words defining words. It must be emphasized into the dictionary. In this case that the word creating function is the selective linking is done by the inherent in any word created by defining part of BUILDS) as selected BUILDS) , and need not be addition- by the bit mask associated with each ally speclfied. defining word.

The execution procedure is begun A major problem exists for meta- by CODE> (for words with a machine compilation (target-compilation) of code execution) or by DOES> (for words new defining words. The compile-time with a high-level execution). Coupling portion must know the run-time compil- from these two words is accomplished ation address corresponding to each by passing an address and bit mask word type. Several methods are from DOES> or CODE> to BUILDS) . currently used. In all cases the syntax is a deviation from the usual The precedence of a word tradition- version suitable for testing on a ally is set by declaring each such resident system. Part of the art of word as IMMEDIATE . In the new form, target compilation is knowing how to this is declared for the defining alter resident defining words to word, not for each word as defined. operate in the target compilation By executing IMMEDIATE after the situation. CODE> or DOES> part, but before the BUILDS) part, the bit mask on the The programmer may declare byte stack is altered to the immediate counts to allocate memory space and form. This mask is applied to all later re-origin compilation to fill words as later defined, so all will in code fragments. Other techniques be immediate. consist of compiling the full struc- ture and then passing address locators Usually colon-definitions and code to previously defined words. In poly- definitions are created 'smudged' so FORTH, dual definitions are used. The that they will not be found during a target compilation definition of our dictionary search. When successfully C-ARRAY example is: compiled, the smudge bit is reset, making the word available for use. : C-ARRAY CREATE ALLOT ;CODE FORTH Other words are much less susceptible : C-ARRAY CREATE ALLOT DOES> + ; to errors of compilation, and so are created un-smudged. The smudge func- It is an exercise in ingenuity to tion is not generally manipulated by determine which parts of the above the user but completed by ; or END- code end up in the target system, and CODE. The smudge bit is contained in which are added to the host compiler. the header count byte. Here is a summary of the meta- By executing SMUDGE after the compiling of our example: CODE> or DOES> part, but before the BUILDS> part, every word later created DOES> + ; will be created smudged. It is a BUILDS> C-ARRAY ALLOT ; system choice how the un-smudging is 10 C-ARRAY DEMO performed. It is suggested that a pointer uniquely specify the current First the COES> compiles + smudged bit address. ; into the target system and passes

FORTH DIMENSIONS II/5 Page 125 the locating parameters to BUILDS> . judged by either usage or the stimu- is an in-line code vector to lation of other methods for this machine code. purpose.

Then the BUILDS> compiles C-ARRAY ALLOT ; into the target system with GLOSSARY the proper object locators for the DOES) part and then places another BUILDS) addr msk --- copy of C-ARRAY ALLOT ; into :he resident compiler so that C-ARRAYS A defining word used in tie form: may be immediately defined for the target system. BUILDS> . . . . ;

Finally, the C-ARRAY in the host to define a defining word . system executes to place a definition The address and mask (left by for DEMO into the target system, either DOES> or CODE>) are placed locate the address of DEMO for later into the definition of to compilation, and finally ALLOT ; specify the header structure for makes the target memory allocation all words created by and and concludes the target definition. locate the execution procedure assigned by . The text The only source changes anticipated between and ; is compiled are the occasional explicit change of to complete the definition of vocabulary to correctly select (during . target compilation) words which affect the application memory. Again, this When executes in the form: is only done for selected defining words.

The key to this method is that the it generates a dictionary entry run-time portion is known before the for and then executes the compile-time portion, and the creation code following to finish of defining words is done uniformly, compilation of . linearly ahead. When executes, it executes the code in the DOES> or CODE> CONCLUSION part preceding . Refer to DOES> or CODE> . A complete implementation of these concepts follows. A six word glossary CODE> --- addr mask expands the explanations given above. This implementation is written in Used in the form: FORTH-79, with system dependent words taken from fig-FORTH. The source of CODE>..(assembly text)..END-CODE each word is identified in the Appendix . to begin the nameless compilation of a sequence of assembler code This construction for BUILDS> is text. The address and mask left offered as a method to regularize the locate this sequence for BUILDS> structure of FORTH at the defining . The mask contains the prece- word level. Its success will be dence and smudge bits and may be

Page 126 FORTH DIMENSIONS II/5 altered by IMMEDIATE and/or SMUDGE to define in the fashion of while still on the stack, before : , but in the immediate form. being compiled by BUILDS> . That is, will execute even when encountered during When a word with a CODE> part ulti- compilation. mately executes, it executes the code between CODE> and END-CODE, SMUDGE addr mask --- addr mask at a machine code level. Execution must ultimately be returned to the Set the smudge bit in the mask to address interpreter NEXT . indicate that all words defined by the defining word being defined DOES> --- addr mask will begin in the 'smudged' condi- tion. This condition prevents a Used in the form: word from being found in a diction- ary search until un-smudged at the DOES> . . . . ; completion of correct compilation.

to begin the nameless compilation of a sequence of high-level code. APPENDIX The address and mask left locate this sequence for BUILDS> . The The example implementation of the mask contains the precedence and new BUILDS> is written in FORTH-79 smudge bits and may be altered by running on a 6502 processor. When IMMEDIATE and/or SMUDGE while still system dependencies occur, the fig- on the stack, before being compiled FORTH methods were used regarding by BUILDS> . error control and dictionary header structure. Here is a tabulation of When a word with a DOES> part ulti- the pedigree of each word (its origin) mately executes, it executes the used in this application. code following DOES> with its own parameter field address automati- Numbers indicate a standard defin- cally placed on the stack. ition from FORTH-79, fig indicates the definition from fig-FORTH. Assembler IMMEDIATE addr mask --- addr mask words are from a 6502 assembler.

Set the precedence bit in the mask to indicate that all words later defined by the defining word being defined will always execute when encountered. :csp ( Immediate words are aids to compil- +! ation, such as: :-

1- i05 CCCNI :+ 135 CSP IF BEGIN DO ." etc. :16 ClmXuI 196 M

>I NOW ?CSP 1 A defining word used in the form:

NOW . . . . ;

FORTH DIMENSIONS II/5 Page 127 FIG GROUPS

Standards--Bill Ragsdale, c/o fig, P.O. Box 1105, San Carlos, CA 94070.

FORML--Kim Harris, P.O. Box 51351, Palo Alto, CA 94303.

8080 Renovation Project--cleaning up the figFORTH 8080 implementation --Terry Holmes, c/o fig, P.O. Box 1105, San Carlos.

f igGRAPH--Howard Pearlmutter, c/o fig P.O. Box.

figSLICE--The FORTH Machine, to be built with bit slice technology-- Martin Schaaf, 202 Palisades Dr., 94015. sca Daly City, CA 3 1 1 3 figTUTOR--how to teach FORTH to 4 J new people--forming--Sam Bassett, c/o 5 fig P.O. Box. 8 9

HELP!! MAYDAY!!

The Editors, not being "old FORTH hands", need experienced LOCAL help in testing submitted programs.

Diversity of systems (fig or not) and terminals much appreciated.

Reply to fig P.O. Box, please!

FORTH PROGRAMMING

Inner Access can provide FORTH programming for a variety of appli- cations and computers. Send for brochure:

Inner Access Corp. PO Box 888 Belmont, CA 94002

Page 128 FORTH DIMENSIONS I1/5 INPUT NUMBER WORD SET ful, leaving only a double integer on the stack. If none of the words are Robert E. Patten successful then nothing is left on the data stack. This outcome is not acceptable because no number was put Purpose on the data stack. Because of this, the last word in the UNTIL: defined The FORTH primitives <# 11 /IS $ word should cause a "Word not defined" SIGN #> allow generalized numeric error. output. This paper presents a gener- alized method for numeric input. INPUT NUMBER WORD SET Met hod

This word set, as implemented, will convert a word placed at HERE, Leave a plus sign, a double number terminated with a trailing blank, to zero, and a true flag on the data a double integer on the data stack. stack in preparation for number The type of input converted is avail- conversion. able in the variable TRAIT. (N)) sign d flag --- d true This word set will allow extentions --- false to include other number and data types (i.e., floating point, triple preci- If flag is true apply sign to sion numbers, and simple string double number and leave number and parsers). true flag else leave only false flag. Most words in this word set expect a flag on the data stack and leave a .N dl flag --- d2 flag flag indicating success or failure of the conversion or test performed. A Substituting zero for blank, con- true flag indicates success. The vert CHR into double number beneath word CHR is an exception. CHR leaving true flag if ok, else leave replaces the flag with a character false flag. from the word at HERE. If the last conversion or test was a failure, CHR >CHR --- addr leaves the same character. If the last operation was a success, CHR Leave the address of a variable leaves the next character on the data which contains a pointer to the stack. last character fetched by CHR.

The defining word N: may be used ? ,NNNS dl flag --- d2 flag to create a word to convert the word at HERE to a double integer. A Allow groups of comma and three successful conversion will leave a digits to be converted to double double integer and a true flag. A number beneath. If no comma return failure will leave only a false true flag. If no three digits flag. If words defined by N: are following the comma then return used to define a word created by false flag. UNTIL: then this new word will, when executed, try each N: created word on ?. flag --- flag the word at HERE until one is success-

FORTH DIMENSIONS II/5 Page 129 If CHR is a period then set DPL to Convert word at here leaving double zero and leave true flag else leave number and a true flag on the data false flag. stack. If word does not convert leave only a false flag on the data ?ASCII flag --- flag stack.

If CHR equals character following N dl flag --- d2 flag ?ASCII then leave true flag else leave false flat. Convert digit at CHR into doriblt number beneath. If successful ?BOTH flag --- flag leave true flag else a false flag.

If flag is true and CHR is a blank NNN dl flag --- d2 flag then leave a true flag else leave a false flag. Do three N leaving true flag if successful else false flag. ?END flag --- flag NS dl flag --- d2 flag If CHR is a blank then leave a true flag else leave a false flag. Do N until failure, leaving a true flag on top of data stack with >CHR ?SIGN false d flag --- sign d flag pointing to last character accepted

If CHR equals - change false flag (N) dl digit --- d2 to a true flag and leave true flag on top else leave false flag on Convert binary digit into number top. be nea t h . ?SKIP flag --- flag REQUIRED flag --- flag

Make flag true. Used to skip past If flag is false exit this word character if flag was false. leaving false flag. If flag is true leave true flag and continue. ASCII -- char TRAIT --- addr Place following character on data stack a8 a number. A variable containing the word count from the last UNTIL: defined CHR flag -- char word.

Add flag to >CHR and fetch char- UNTIL : acter at >CHR to data stack. A defining word used in the form: N: A definining word used in the form : UNTIL: . . . ; N: . . . ; Words created by UNTIL: are like --- d true colon-definitions except the run --- false time function is to execute words in the definition until there is a true flag on the data stack, then exit the word leaving the word count of the words executed in the variable TRAIT.

Page 130 FORTH DIMENSIONS 11/ 5 NEW PRODUCTS FORTH for OSI

by Forth-Gear

Forth-Gear is pleased to announce the release of a complete FORTH soft- ware package for several models of Ohio Scientific Instruments computers. The Forth Interest Group model lan- guage runs under OSI's Disk Operating System OS65D-3.2, but high level FORTH DOS words are implemeted in FORTH for full compatibility with fig-standard extensions. A line editor is included for the creation and disk storage of FORTH programs. A 6502 assembler per- mits the use of machine code routines as FORTH definitions. The editor and assembler may both be extended by the creation of new definitions in high level FORTH.

Included with the package are several utility programs in FORTH, including a RAM Dump, video graphics, data disk initializer (may use all tracks except track zero), a sample machine code routine (screen clear), and a system disk optimizer.

Minimal system requirements are 24 Kilobytes of RAM and one disk drive. System attributes beyond the minimal requirements may be fully utilized by regenerating the system disk with the optimizer program. Two systems are currently available: The 5 114" disk version works on all C2-4P and C4 models. The 8" disk version works on all C2-8P, C8P, C2-OEM, and C3 models with either the polled keyboard or a serial terminal. Superboard, ClP, and C2 versions will be available very soon. ATARI DISKETTE A single-user system consisting of Diskette and documentation for fig- a disk (specify size) and fifty page FORTH on ATARI computers. Runs on user manual is available from Consumer one disk drive and 16K RAM. Has full Computers, 8907 La Mesa Blvd., screen editor and extensions. $50.00 La Mesa, California 92041, for the introductory price of $69.95 prepaid. Bob Consalves Telephone (714) 698-8088 9 to 5 PST. c/o Pink Noise Studios 1411 Center Street Oakland, CA 94607

FORTH DIMENSIONS I1/5 Page 131 STRUCTURED PROGRAM MlNG EXTERNAL. Since debugging in FORTH BY ADDING MODULES TO FORTH proceeds from the bottom up, once you have debugged these local routines, Dewey Val Schorre you will have no further need to refer to them from the console. They will only be referenced from the external Structured programming is a strong part of the module. Modules can be point of FORTH, yet there is one lan- nested to arbitrary depth. In other guage feature important for structured words, one module can be made local programming which is currently absent with respect to another by defining in FORTH. This feature is called a it between the words INTERNAL and module in the programming language EXTERNAL. MODULA, and appears under other names in other languages, such as procedure Now let's consider matters of in PASCAL. It can, however, be easily style. The matching words INTERNAL, added by defining three one-line EXTERNAL and MODULE should all appear routines. on the same screen. When modules are to be nested, one should not actually The names of these routines are: write the lower level module between INTERNAL, EXTERNAL and MODULE. A the words INTERNAL and EXTERNAL, but module is a portion of a program should write a LOAD command that between the words INTERNAL and refers to the screen containing the MODULE. Definitions of constants, lower level module. The screens of a variables and routines which are FORTH program should be organized in local to the module are written a tree structure. The starting screen between the words INTERNAL and which you LOAD to compile the program EXTERNAL. Definitions which are to is a module which LOAD'S the next be used outside the module are level modules. written between the words EXTERNAL and MODULE. Screens are much better for struc- tured programming than the conven- One of the most common uses of tional character string file because modules is to create local variables they can be chained together in this for a routine. These variables are tree structured manner. You will defined between INTERNAL and EXTERNAL. write a module for one program, and The routine which references them is when you want to use it in another defined between EXTERNAL and MODULE. program, you don't have to edit it Notice that this module feature is into the new program or add it to a more general than the local variable library. All you have to do is to feature of other programming lan- reference it with a LOAD command. guages, in that several routines can share local variables. Such sharing There is an efficiency advantage is important, not so much from the to the use of modules. One minor standpoint of saving space, but advantage is that compilation speed because it provides a means of is improved because the dictionary communication between the routines. that has to be searched is shorter. The more important advantage of If you have written any local rou- saving dictionary space is not tines between the words INTERNAL and realized with this simple implementa- EXTERNAL, then in order to debug them, tion, which changes a link in the you will have to delete the word dictionary. To save space, one would INTERNAL and put a ;S before the word have to implement a dictionary that

Page 132 FORTH DIMENSIONS 11/ 5 was separate from the compiled code. The evening meetings, both Moreover, this dictionary would not Wednesday and Thursday, had formal be a simple push-down stack, because technical sessions which evolved into the storage freed by the word MODULE quite open, informal, and productive is not the last information entered discussions. The participants had to into the dictionary. be persuaded to break up to move to the scheduled social gatherings over The words needed to define modules wine and cheese. are as follows:

: IKTERNAL ( --> ADDR) CURRENT @ @ ; SUMMARY OF SESSIONS : EXTERNAL ( --> ADDR) HERE ; : MODULE( ADDRl ADDR2 --> )PFA LFA ! ; The number of people presenting papers was so great (almost 40) that sessions were scheduled from Wednesday FORML CONFERENCE afternoon all the way to Friday after- A Report on the noon. Topics of sessions, together Second FOWL Conference with their chairmen, were:

FORTH-79 Standard The Second Conference of the Forth Bill Ragsdale Modification Laboratory (FORML) was held over Thanksgiving, November 26 Implementation Generalities to 28, 1980, at the Asilomar Con- Don Colburn ference Center, Pacific Grove, California (some 120 miles south of Implementation Specifics San Francisco). Dave Boulton

The weather was unseasonably beau- Concurrency tiful, as the rainy season, normally Terry Holmes starting in November, was late. Most conference attendees managed to find FORTti Language Topics some free time to enjoy the beach and George Lyons wooded areas. Other Languages With the way smoothed by a core Jon Spencer crew who showed up Tuesday, the major- ity of participants arrived for lunch Me taFORTH Wednesday, and launched right into a Armand Gamberra full schedule of technical sessions. Programming Methodology There were 65 conference atten- Eric Welch dees, with enough of them bringing family to raise the count to 96 people Appllca t ions at Asilomar in connection with FORML. Hans Niewenhuijzen

The rooms were in scattered well- landscaped buildings. Meals were In addition, Kim Harris, the Con- provided in a central dining building, ference Chairman, opened the Confer- and were generally praised. Thanks- ence with a welcome and a review of giving noon dinner, a deluxe buffet FORML-1, London, January 1980. Kim meal, was a special treat. also closed the final session.

FORTH DIMENSIONS I1/5 Page 133 As one example of a conference paper, "Adding Modules to FORTH" by LETTERS Dewey Val Schorre, gave a mechanism for setting up words which are local J. E. Rickenbacker pointed out that to a "module"--a sequence of FORTH the JMP ($xxFF) of the fig-FORTH inner code. His mechanism involves only interpreter does not work on a h502. three FORTH words, two of which already exist in FIG-FORTH. His That is right, but the fig-FORTH novel but straightforward way of compiler aut omd t i ca 11y tcs t s for t hi s using these three simple words pro- condition and 'ivcids cridirig a CtA in vides many of the benefits of VOCABU- FF. 1.ARY with less overhead, and by focusing on modularity, it can lead The only probleni WCLI~S during to clearer programs. initial installation w\,c,ii band assembly is required. Since 6502 Another item of particular interest assemblers, unlike FCJRTH, are inf 1c.x was George Lyons's paper on Entity ible you just have to sit there help- Sets. His proposal is very econom- less watching them mdke the same dumb ically implemented, and allows, at mistake at each new assembly and then compile time, selection from lists of add a correction when tlie assembler is identically-named operators, such as finished. Since fig-FORTH has ahout @ ! + , based on data type. 210 definitions, the chances are pretty good (about 210 out of 216) These and other wonders will be that a CFA will end in FF. published in the Proceedings of the Conference. This should be ready by My advice would be to leave the the end of February, and will be sold patch in until the system is pretty by FIG. well debugged and then install the jump indirect scheme of the f ig-FORTH LESS FORMAL OBSERVATIONS model. It would be a shame to permanently slow down the system At the Wednesday evening technical unnecessarily because of an initial session an informal discussion on installation inconvenience which is various topics included "Notes on the primarily the fault of the inflexi- Evolution of a FORTH Programmer" by bility of the 6502 assembler. Charles Moore, in which he described how his own programming style had As to Mr. Rickenbacker's query on matured. a FORTH assembler vocabulary, he may find Programma International's version On the final day the question was of APPLE-FORTH helpful. The system brought up of whether FORTH was a isn't FORTH, it is something like programming language or a religion. FORTH. However they have a FORTH- The consensus was: Yes! In the same like assembler in their system which discussion the expression "born-again may be helpful. The op-codes have programmer" appeared. (It is in com- been analyzed for postfix operation, petition for catch-phrase of the year etc. with "black-belt programmer", which was heard at the FIG Convention in FORTH is beautiful. San Mateo the following day.) Edgar H. Fey Jr. ;s G. Maverick La Grange, IL

Page 134 FORTK DIMENSIONS II/5 LYONS' DEN EMPLOYMENT WANTED

Chairman of the FORTH Bit Slice Implr- In the course of implementing the mentation Team (4th BIT) desires a FIG model on my computer I have junior programmer position working in noticed that the word NOT is in the a FORTH environment. (Also know assembler vocabulary but not in the COBOL & BASIC.) high level glossary. Instead 01 is used for logical negation in high Contact: Martin Schaaf level code. Defining NOT as a 202 Palasades Dr. synonym for O= in the main kernel Daly City, CA 94015 glossary might be useful. Code would (415) 992-4784 (eves.) be a little more readable by disting- uishing between the operations of testing whether a number on the stack HELP WANTED from a mathematical formula is zero, and logically negating a boolean flag HELP 4TH BIT left on the stack by a relational operator, even though the code used to perform these two operations is With the implementation of a FORTH the same. But a stronger need for a machine in AMD bit slice technology. high level NOT occurs when floating If you're a hardware or microcode point or other data types in addition expert we can use your help. (This to the standard integer type is imple- is a volunteer FORML project.) mented by a vocabulary containing redefinitions of the mathematical Contact: Martin Schaaf operators. In that case a new 01 Chairman, 4th Bit would be defined to test, say, whether 202 Palasades Dr. a floating point number were zero, and Daly City, CA 94015 this new O= could not be used for log- ical negation. Of course, the exist- ing practice seems to be to define new operators with unique names such MEETINGS as FO= instead of redefining the kernel names, avoiding this problem. LA fig User's Group Also, a user can always add a synony- October 1980 mous NOT to the FORTH vocabulary before redefining 0- and the other The LA group continued to experi- operators in the vocabulary for a new ment with format on its second data type. Once using NOT in code meeting. It will continue to meet on written in the terminology of the new the fourth Saturday each month at the vocabulary, however, one might as Allstate Savings and Loan located at well use it for code in the kernel 8800 S. Sepulveda Blvd., 1/2 mile terminology as well, and then such north of the LA airport. could not be compiled by the standard kernel. So, why not add a NOT? The agenda this month called for a FIG meeting at 11, lunch at noon, and George B. Lyons a FORML session at 1 patterned after Jersey, City, NJ our northern neighbors.

ARE YOU A ------FIGGER? YOU CAN BE! RENEW TODAY!

FORTH DIMENSIONS II/5 Page 135 At 11, a 20 minute random access L.A. fig Meeting was followed by an introduction by November 1980 each of the 40 people present. The remaining half hour before lunch was The November meeting was slightly evenly divided between a summary of smaller and less formal than the the FORTH '79 document given by Jon preceding meetings. After a short Spencer, and a series of short round of introductions, we were announcements. These included a treated to a demo of a new set of reminder about the Asilomar happen- FORTH sys t em/appl icat ion t 001 s by the ing, a query about target compilers author, Louis Barnett of Decision for the f igFORTH environment, a Resources Corp. He has an Advanced suggestion that the LA and northern Directory, File, and Screen Editor CA group exchange copies of notes or system which fits on top of fig-FORTH. handouts from the meetings, a brief I have looked at implementing a interchange of thoughts on program similar system in the past. He has exchange leading to the idea of a thought out the tradeoffs of flexibil- uniform digital cassette standard, ity, speed, and keeping compatible requests for assemblers and model with existing FORTH block formats. corrections, and finally a parallel He allows the blocks to be interpreted was drawn between the science fiction in the traditional manner (by block group's use of an "Amateur press !I), as well as by file name and rela- association" as a potentially useful tive block number. He uses buffer distribution channel. pools and bitmaps to use all available disk space. It keeps a list of block From 1:15 to 4, Jon Spencer numbers within a named file. Best of presented a FORML section which all, it allows editing, printing, and covered 3 topics: compiling by named file. I was suf- ficiently impressed to buy a copy on 1. Language processing. the spot. 2. Address binding and examples of a FORTH linker. After lunch, I presented an intro- 3. A continuation of his talk of duction to a tool I have been working last month on an algebraic on. It is used to build stack dia- expression evaulator for FORTH. grams interactively for screens or colon definitions from the source We all offer our thanks to Phillip screen coupled with symbolic element Wasson who has organized the LA group. names entered from the console. I He is available at 213-649-1428 for will write it up for a future issue details of the coming meeting. To of F.D. get things rolling as far as program and information exchange, I volun- ;s Barry A. Cole teered as the LAFIG librarian. In 2 sessions, this has already expanded to writing a review for FORTH Dimen- sions and keeping track of spare copies of the handouts. I can be reached evenings from 7 to midnight RENEW NOW! at 213-390-3851.

;s Barry A. Cole RENEW TODAY!

Page 136 FORTH DIMENSIONS 11/ 5 LA MEETING Bill mentioned the European approach-- dynamic and oneway. In contrast, The next meeting of the "L.A. FORTH FORTH, INC. has a 4 level chain and Users Group" will be the FORTH-79 Standard uses expl icl t chaining by vocabulary-name invoca- at: Allstate Savings 6 Loan t ion. Community Room 8800 S. Sepulveda Blvd. Handouts iacluded a FORTH machine Los Angeles, CA proposal by Martin Schaaf, Ragsdale's (1/2 mile ncrth of LAX) CASE statement, a workshop announce- ment (for December) and Product January 24, 1980 ("FORTH" Saturday) Reviews of Laboratory Flicrosystems' 11-12 AM General session 2-80 fig-FORTH and SBC-FORTH from 12- 1 PM Lunch break Zendex Corp., by C.H. Ting. Introduc- 1- 3 PM FOWL Workshop tions included:

Info: Philip Wasson (213) 649-1428 - Sam Bassett is writing a text on FORTH For Beginners. - Kim Harris' Humbolt State Univ. FOWL class will be held the week of October 1980 23-27 March. - Ron Gremban offered a 4th Henry Laxen opened with a discus- programming job. sion session on the problems of teach- - FORTH will be mentioned in the ing FORTH. This produced a number of next WHOLE EARTH CATALOG. ideas ranging from subglossaries and - Bill Ragsdale had been elected reorganizations of glossaries, to to the Board of Directors of comments on style and the categoriza- FORTH, INC. tion of tools. An anecdote by Kim - Future fig meetings will be Harris described a class of experien- held underneath Penneys just ced FORTH programmers all FORTHing a East of Liberty House, Hayward. traffic intersection problem only to be startled to discover that Charles ;s Jay Melvin Moore's solution used no IFs (the dictionary already is a link of IFs !> FORML November 1980 Northern California November 1980 FORML - Klaus Schleisiek spoke about his FORTH implementation of an FORTH-79 STANDARD: Bill Ragsdale audio synthesizer which we heard on a summarized details of the just- cassette recording. The input device published standard which had been has e lightpen and output was by 64 worked out last year at Catalina speakers. Digital counters were Island. Handed out was a FORTH-79 organized in a linked list of regis- Standard HANDY REFERENCE card and a ters comprising a table of sounds two-page FORTH-79 Standard Required searched by NEXT. The structure of Word Set and requirements sheet with Klaus' program was depicted in discus- system errors and errors of usage sion and on a half dozen xeroxed specified. About vocabulary chaining, screens.

FORTH DIMENSIONS II/5 Page 137 Northern Ca 1 if o rnia FORTH COURSE October 1980 PEOPLE, COMPUTERS, AhD Bok Lee described STOIC, "A baroque FORTH PROGRAMMING elaboration of FORTH". This dialect differs from figFORTH by virtue of its DATE third stack (Loopstack for I para- meters) and its 4th stack which March 23-27, 1981 handles up to four vocabularies used, a compile buffer (which can be simu- COURSE lated by :: definitions in FORTH) and by its file system which is not The course is an intensive five screen-dependent but of indefinite day program on the use of FORTH. length. The STOIC presentation was Topics are to incluse usage, followed by a panel debate consisting extension and internals of the of Kim Harris, Bob Fleming, Dave FORTH language, compiler, assen- Bolton, Bill Ragsdale and B.W. Lee bler, virtual machine, multi- where it was unanimously decided "to tasking operating system, mass each his own". General agreement was storage, virtual memory manager, made about STOIC or FORTH's ability and file system. Computers will to simulate features of each other. be used for demonstrations and The following differences seemed class exercises. Due to class noteworthy: size limitations only twenty participants will be permitted. - STOIC has some old style Please register as soon as (FORTRAN?) mechanisms reflect- possible but no later than March ing author Sack's incomprehen- 1, 1981. The cost will be $100, sion of some of author Moore's or $140 with 3 units of credit. concepts. The manual "Using FORTH" will be - STOIC is conceptually not available for an additional $25. verbal, as is FORTH. - STOIC is very well documented! Send payment to: - STOIC is not supported by a group (like fig) and, conse- Barbara Yanosko quently, Office of Continuing Education - STOIC is not portable. Humboldt State University Arcata, CA 95521 Mr. Bok's handouts included a (sample) DUMP program, NORTHSTAR and LOCATION CP/M memory maps for STOIC and a decompiler. Other meeting handouts Humboldt State is located in included a structured (FIND) by Mike Arcata, California, six miles Perry (which appears to be 8080 north of Eureka and about 300 coded), a 6502 assembler with heavy miles north of San Francisco. commenting by Tom Zimmer as well as Arcata has bus and plane service Zimmer's ad for tiny PASCAL, ROM and from San Francisco and Portland. disk based OSI FORTH and Asilomar Motels are available for lodging. FORML details. C.H. Ting introduced Transportation will be available his just published FORTH SYSTEMS from the local "Motel 6". Other GUIDE, which is enlightening. Sam motels are within walking distance. Daniel volunteered to take on my For reservations, contact: scribeship abandoned due to marriage and relocation in L.A. Motel 6 4755 Valley West Blvd. ;s Jay Melvin Arcata, CA 95501

Page 138 FORTH DIMENSIONS 11/5 IKFORMATION 5. Regional groups are springing up all over the U.S. New For other information contact: groups are now meeting in Los Angeles, Boston, Dallas, San Professor Ronald Zammit Diego, San Francisco, and Physics Department approximately 20 other cities Humbo Id t State University across the country. Arcata, CA 95521 Following a panel sessicln on the (707)826-3275 FORML conference at Asilomar, Charles (707)826-3276 Moore of FORTH, Inc., closed the morn- ing session with a reminder that it is the very flexibility and versatil- ity of FORTH which will cause more FIG CONVENTION problems as more people become ac- quainted with it. In particular, we The second annual FIG Convention must be able to demonstrate to large was a big success with 250 FORTH mainframe users that FORTH is also users, dealers, and enthusiasts applicable in their environment. attending a full day of sessions on FORTH and FORTH-related subjects. The afternoon session was high- The Villa Hotel in San Mateo, CA lighted by two very interesting pre- provided the setting this year. sentations. The first was on software marketing, pointing out very clearly In the annual report, Bill the differences in professional and Ragsdale mentioned some of the amateur approaches to selling of milestones passes by FIG in 1980: software. The second presentation was by Dr. Hans Nieuwenhuizen, of the 1. Total membership is now 2,044. University of Utretch in Holland, About 1200 new members joined regarding the implementation of High this year, primarily due to Level Languages in FORTH. Dr. the BYTE issue devoted to the Nieuwenhuizen reported running BASIC, FORTH language. PASCAL, and LISP systems, written entirely in FORTH, at the University 2. Roy Martens was hired this of Utretch. (Please do not write Dr. year as the full-time publisher Nieuwenhuizen concerning availability of FORTH DIMENSIONS, and is of this software. When it is ready also taking over responsibility for distribution, an announcement for all mail-order and tele- will be made through FORTH DIMEN- phone inquiries. SIONS. )

3. The first college-level course The formal part of the convention in FORTH was taught by Kim concluded with presentations from Harris in 1980. An0 t her some of the many vendors of FORTH course, to be offered in 1981, systems and software. will give college credit for completion. After a short interlude for infor- mal discussion and attitude adjust- 4. The FORTH-79 Standard was ment, Mr. Allen Taylor, author of the approved just prior to the Taylor Report in Computerworld, was convention, and copies are the guest speaker at the now- available through FIG mail traditional evening banquet. order. ;s S. Daniel

FORTH DIMENSIONS II/5 Page 139 MORE LETTERS Dear FIG (Whoever you are), Just a little note to let you know Since I seem to be the first OSI that I received all the FIG material user to have the FIG model installed that I ordered. I would like to know and fully operational, I thought that if the 8080 listing is available on you might add my company name to your IBM formatted single density 8" disk- list of vendors. I have been extreme- ettes and if the fig-FORTH model ly faithful to the model, changing listed in the Installation Manual, only the 1/0 and -DISC. Everything i.e., Screen Nos. 3-8, 12-80, 87-97, works just fine, and by that I mean a is also available on an IBM format 8" -lot better than OSI's standard system single density diskette? I don't software. I did find a miscalculated relish having to type in all that branch (forward instead of backward) material, to get fig-FORTH up and and the address of ;S was left off of running. the end of UPDATE (with lethal result) in case you are interested. Unfortun- I have taken the liberty to spread ately, I couldn't use the ROM monitor the word about fig-FORTH in my compu- for MON since it blows out the OSI ter club and have attached copies of DOS. Instead MON jumps to the DOS two of our newsletters, in which command interpreter, which is more reference to it has been made, see useful than the OSI ROM monitor, VCC NL Issue 109- bottom p. 3 and anyway. Issue 112- middle p.2.

I feel that I am in a position to S. Lieberman fully support the system, since I Valley Computer Club know OSI's hardware and DOS inside- P.O. Box 6545 out, and also it appears that I may Burbank, CA 91510 have their (OSI's) cooperation and even mention in future advertisements. (An 8080 figFORTH system on 8" disk- ette for CP/M systems is available I have enclosed a press release from Forthright Enterprises - P.O. Box which describes system requirements, 50911, Palo Alto, CA 94303 -- Ed.) ordering information, and price.

Guy T. Grotke San Diego, CA Here is a program you are welcome to publish in FORTH Dimensions.

We are soliciting comments, sugges- Lyall Morrill tions and bug reports concerning the San Francisco, CA fig-FORTH 8080 source listing. Work on converting this to the 1979 Standard will begin in early Februry, 1981, so please make submissions as soon as possible to:

8080 Renovation Project c/o FORTH Interest Group P.O. Box 1105 San Carlos, CA 94070

Terry Holmes

Page 140 FORTH DIMENSIONS II/5 Just a line to let you know of a The video editor presented as an couple of FORTH activities at this example of CASE use by Major Robert end of the country. Here at Temple U Selzer in FORTH DIMENSIONS v. 11/3, we have a lab equipped with 25 AIM p. 83 is super. systems. Microprocessor Systems is a 56-hour lecture / 28-hour hands-on Enclosed is a direct extension of course of which about 12/6 hours are Major Selzer's work to edit ASCII allotted to AIM Assembler. files over several consecutive screens. It is used in the form: I am now testing both Rehnke's V 1.0 FORTH cassette and Rockwell's V nl n2 FEDIT 1.3 FORTH ROM chips. I expect to teach one or the other in place of where nl is the first screen in the the AIM Assembler this term. file and n2 is the last.

On March 21st the IEEE UPDATE FEDIT contains all the commands of Committee is running an all-day tu- Major Selzer's VEDIT and works in the torial on FORTH. At that time I hope same manner. ESC exits the editor and to demonstrate FORTH transportability the cursor position is controlled by between, say, AIM and PET or Apple. the single keystrokes LEFT, RIGHT, UP, I wonder whether anything has been DOWN AND RETURN. When the top or published on this sort of demonstra- bottom boundary of the display is tion. reached a new display of either the next or the previous 24 lines in the Karl V. Amatneek file is presented for editing. Director of Education Committee for Professional The added commands are RUB which UPDATE deletes characters and two double key- Wyndmoor, PA stroke commands HOME and TAB.

HOME followed by DOWN or UP (No, but if you'd like to write produces a display of the next or one... Ed.) previous 24 lines respectively independent of the position of the cursor. Two successive strokes of HOME produce a new display with the line containing the cursor in the old display at the center of the new I get a great deal of your mail. display. These commands provide I work for GTE LENKURT, 1105 Old rather rapid traversal of a file and County Road, San Carlos. Those idiots positioning of the file on the in the post office can't distinguish display. . that from P.O. Box 1105 and our names are not that dissimilar, I guess. At the end of a file, additional numbered but blank lines may be dis- Please get another box number. played. Text written into this area will not be put into the buffer. M. Mohler Similarly if the first line of the San Carlos, CA file ends up in the middle of a display, the area above the first line is protected. (Guess we're TOO popular -- Ed.)

FORTH DIMENSIONS II/5 Page 141 The TAB key is used to erase, delete and replace lines from PAD. TAB followed by E erases the line containing the cursor. TAB followed by D erases the line and holds the line in the text output buffer PAD. The cursor may then be moved to any position in the file, including other screeiis, and the contents of PAD may be put on the new line by the key- strokes TAB then P. TAB followed by H places the cursor's line in PAD without deleting the line. These commands use the fig-FORTH line editor definitions E, D, R (REPL in the listing) and H.

Major Selzer's definition of CASE does not work in fig-FORTH with its compiler security features. An appro- priate definition of his CASE word for fig-FORTH is shown on line 10. The word OFF on line 68 controls a switch in my EMIT to stop output to my printer. All other words should be standard fig-FORTH. The terminal dependent cursor position sequence used by Selzer for his ADM-3A terminal (YXCUR, line 3) also works on my SOROC IQ 120 terminal.

I have found FEDIT to be a conve- nient editing tool which I use along with the fig-FORTH editor. Eventu- ally, I suppose, my entire fig-FORTH editor will find its way into FEDIT. I hope your readers will also find it convenient. I also hope FEDIT lays to rest some of the recent criticism of FORTH (in BYTE) concerning its rudimentary editing facilities. My thanks to all of you in FIG for your efforts in promotion FORTH.

Edgar H. Fey LaGrange, IL In addition to an extensive cuminand NEW PRODUCTS set, there are many lower level primi- tives which may be combined to define 6800 d 6809 FORTH a virtually unlimited set of comm.inds.

t FORTH Computer system hardwarc sliould FORTH System $100 include :

One or more 8" IBM compatible t FORTH+ floppy disk drives plus Assembler, CRT Editor $250 Enough memory to support 6K f irmFORTH bytes (on an 8 bit processor) produces compacted for FMS-4 in addition to the ROhable code $350 FORTH nucleus and any other concurrently resident applica- tions. Kenyon Microsystems 3350 Walnut Bend An 808018085 or 280 cpu. Houston, Texas 77042 Phone (713)978-6933 A CRT or printing terminal which supports upper and lower case. CRT EDITOR AND FILE MANAGEMENT SYSTEM System software should include:

The Decision Resources File Manage- fig-FORTH compatible nucleus ment System (FMS-4) for the FORTH or equivalent. language has extensive vocabulary for creating, maintaining and accessing An assembler for the target name files. cpu. DRC can supply an 8080 assembler at additional cost. Disk space is dynamically allocated and deallocated so there is never any FMS-4 source code is delivered need to reorganize a disk. From the ready to run (on compatible systems) user viewpoint, access is to logical on a single density 8" soft sectored records; FMS-4 performs the mapping to diskette (IBM 3740). physical screens. A complete user manual describing Files may be referenced by nalce all facets of FMS-4 operation is without concern for the physical provided. The manual includes an location of the file on disk. FMS-4 extensive glossary which defines and supports sequential and direct access documents the usage of each word in while preserving FORTH's facilities the FMS vocabulary. for addressing screens by number. Wordsmith is a CRT screen editor FMS-4 maintains a file directory of which is integrated with Decision up to 47 entries. Each file may con- Resources' File Management System - sist of from one to 246 records (1024 FMS-4. The combination is an espe- bytes per screen) in a single volume cially powerful file oriented editor (single density diskette). It is also which combines the extensive disk possible to extend FMS to control space management facilities of FMS-4 multiple volume files and to support with the flexibility and immediacy of larger directories. on-screen editing.

FORTH DIMENSIONS II/5 Page 143 The fc record being edited is TRS- 3 DISKETTES continuously displayed on the CRT and all changes are immediately visible. Advanced Technology Corp. of Knox- There are 41 editing commands includ- ville, TN, is presently distributing ing: multidirectional cursor move- its fig-STANDARD FORTH version ment, record to record scrolling, (TFORTH) customized for the Radio record insert and delete, string Shack TRS-80. Included in this search and replace, text block move- package are: assemblers, 'TRACE' ment and many more. function for generating minimum system /CMD files, POINT, SET, CLS The FMS-4 and Wordsmi th commands for graphics use, Floating Packages point package, 1/0 package (LPT Out- put) and variable number base to base Wordsmith and FMS-4 source code is 32. delivered ready to run (on compatible systems) on a single density 8" soft The language is supplied on either sectored diskette (IBM 3740). 80 or 40 track 5-1/4" diskette for $129.95 and the manual is also Complete user manuals for each included. system are provided. This product may be purchased from: Pricing Sirius Systems Single noncommercial user license: 7528 Oak Ridge Highway FMS-4 $50 Knoxville, TN 37921 Wordsmith (with FMS-4) $95 or Manual only: Wordsmith $15 QC Microsystems FMS-4 $15 P.O. Box 401326 Both $25 Garland, TX 75040 (credited toward purchase of full package) or directly from us,

California residents add 6% sales tax Advanced Technology Corp. Shipping and handling : $2 SO 1617 Euclid Avenue Knoxville, TN 37924 Commercial Purchasers should contact (615) 525-1632 Decision Resources.

Dec Is i on Re sources Corporat Ion 28203 Ridgefern Court Rancho Palos Verdes, CA 90274 (213) 377-3533.

AREYOUA ------FIGGER? YOU CAN BE! RENEW TODAY!

Page 144 FORTH DIMENSIONS 11/5 PRODUCT REVIEWS the chip uses some Interrupt scheme to drive the terminal. I was not by able to get the detailed information C.H. Ting on how the interrupts were supposed to go from Zendex. I do not have a disc drive in the system to test out 2-80 fig-FORTH by Ray Duncan of the disc interface. Other things ran Labor at ory Microsystems, 4147 satisfactorily. I was able to talk Beethoven St., Los Angeles, CA 90066 to the parallel 1/0 ports using the (213) 390-9292. assembler.

Two 8" single density diskettes, This type of ROM based FORTH $25 .OO. machine can be very powerful for programmable controllers and low cost The first disc is a CP/M disc con- development systems if some non- taining 2-80 assembly source codes, volatile memories like core or hex object codes, user instructions, battery-backed CMOS were added. fig-FORTH Installation Manual, and fig-FORTH Glossary. The second disk A very nice thing they did in the is in FORTH block format containing manual was to include the code or system configurations, a line editor, colon definitions in the Glossary, a poem 'The Theory That Jack Built' making it infinitely more useful as a by F. Winsor, Eight Queens Problem by reference. J. Levan, Towers of Hanoi by P. Midnight, Breakforth by A. Schaeffer, and some utilities. NEW PRODUCTS I do not have a system that can run the 2-80 codes. However, the source APPLE figFORTH codes seem to be carefully done and follow faithfully the fig-FORTH 8080 model. Lots of typing was put in to Including an Assembler, Screen have the entire Installation Manual Editor, Source Code and associated and Glossary entered on disc. The compiler, with some documentation on games were published in FORTH Dimen- disk. No other documentation, support sions. The amount of information or instruction. Source listing will offered at this price is unbelievable. be available from fig in mid-81. I just wish that I had a machine that Apple format disk - $30.00. could run it. George Lyons, 280 Henderson St., SBC-FORTH from Zendex Corp., 6398 Jersey City, NJ 07302. Dougherty Rd., Dublin, CA 94566 (415) 829-1284.

Four 2716 EPROM's to run in an SBC-80/20 board with SBC-201 single CROMEMCO DISKETTE density disk. $450.00. A fig-FORTH 5-1/2" disk with 280 I had the PROM's installed in a assembler for Cromemco machines. System 80/204. It ran only after I $42.00 jumpered the CTS/ and RTS/ pins of the 8251 serial 1/0 chip. Obviously Nautilus Systems PO Box 1098 Santa Cruz, CA 95061

FORTH DIMENSIONS II/5 Page 145 NEW PRODUCTS OSI DISC "Systems Guide to f ig-FORTH" Tiny PASCAL written in fig-FORTH. Machine Readable for OSI-C2-8P. Author: C.H. Ting Single or Dual Floppy System 8" disc. 156 14th Ave. Cost: $60.00 San Mateo, CA 94402 This includes fig-FORTH with fig editor and assembler for FREE! 132 pages, $20.00 OSI C2 or C3 fig-FORTH on 8" disc. Cost: $45.00 This book is meant to be a bridge Includes assembler and fig editor between "Using FORTH" and the "fig- FORTH Installation Manual", and to serve as a road map to the latter. Tom Zimmer It might also be used as a collection 292 Falcato Dr. of programming examples for those Milpitas, CA 95035 studying "Using FORTH". (408) 245-7522 ext. 3161 or (408) 263-8859. In it, I have tried to arrange the f ig-FORTH source codes into logical groups: Text Interpreter, Address Interpreter, Error Handler, Terminal tinyPASCAL I/O, Numeric Conversions, Dictionary, Virtual Memory, Defining Words, Con- Printed listing of tinyPASCAL in trol Structures, and Editor. Exten- fig-FORTH. sive comments are thrown in between source codes at the risk of offending $10.00 US/Canada, $14.00 Overseas. the reader's intelligence. Occasion- Check (US bank), VISA or Master ally flow charts (horror of horrors!) Charge. are used to give graphic illustra- tions to some complicated words or Mountain View Press procedures. PO Box 4656 Mt. View, CA 94040 There is a very wide gap between the front page and the back page of the FORTH Handy Reference Card. It is relatively easy to manipulate the stacks and to write colon definitions FORTH Version 1.7 to solve programming problems. The concepts behind words of system func- Cap'n Software FORTH Ver. 1.7 for tions, like INTERPRET, [ , ] , COM- Apple I1 (TM) or Apple 11+ computers PILE, VOCABULARY, DEFINITIONS are is the FORTH Interest Group (FIG) very difficult to comprehend, not to language, plus extensive program mention . One development tools and special Apple cannot understand the FORTH system options. $175.00. and how it does all these wonderful things by reading the source codes or by searching the glossary. These Cap'n Software documents are vehicles to define the P.O. Box 575 FORTH system, not to promote under- San Francisco, CA 94101. standing of them.

Page 146 FORTH DIMENSIONS II/5 C) As an option, either a text SEPARATED HEADS string or a string of program- Klaus Schleisiek mable graphics characters to be displayed above, below, or to either side of the dot. Memory in RAM-based systems can be used more efficiently by means of a Thus, every "dot" served a double "Symbol Dictionary Area ," which allows purpose. On the one hand, it des- words and/or name and link fields cribed a portion of the display which are needed only at compile time itself which had to flash on the to be thrown away after compilation. screen. Secondly, it supplied the Incremental use of these techniques key to a large keyed CASE statement will result in more efficient memory which associated the dot with the usage and will. also encourage the use function to be performed when the of more and shorter definitions lightpen was pointed to it. In other because there is no longer the need words, the definitions of the dots to pay the penalty of taking up themselves were only needed at memory space with numerous name and compile time . link fields. The dot definitions were used to In the course of a two-year create a densely packed "image" defin- project I developed some tools which ition to flash the picture on the allow a significant compression of screen, while the addresses of the code in RAM-based systems. I also dot locations were used as keys in feel these methods will have a sig- the CASE statement. So, to be memory nificant impact on programming style, efficient, I wanted to set up some particularly because they will encour- mechanism which would allow the pre- age the use of more and shorter sence of "symbols" at compile time definitions. The followicg is an that could then be thrown away after explanation of these various functions compilation to free memory. By in a somewhat historical order. "symbol" I mean any legal FORTH definition that is only needed at My programming task was to develop compile time. This led to the idea a lightpen-operated sound system, of dividing the dictionary into "main which would allow control of a number dictionary" and " symbol dictionary ." of small sound synthesizers by point- ing a lightpen to various dots, light Figure 1 shows the arrangement of potentiometers, and the like on a this scheme based on the 6502's unique video display. There was to be no memory mapping. keyboard intervention. A "dot" was put together by compiling a word which associated the following information: I A) The shape of the dot itself as 1 an address of some programmable I character. I I B) The dot's location on the I screen as an address relative I to the upper left hand corner 1 I of the screen. I I I

Figure 1

FORTE DIMENSIONS II/5 Page 147 I soon realized that most of the are made to the word, its CFA is words defined in my programs would contained in the memory location next never be used again after compilation to the code field address of (CFA) . and started thinking about putting the name and linkfield (head) of a defini- The function of (CFA) (SCR 1/23) tion into the symbol dictionary, and is either to compile the execution compiling the code field and parameter address of code into the dictionary field only into the main dictionary. (when the word is subsequently used I wanted to do it in a fashion similar in a definition), or to execute the to SYMBOL DIC and MAIN DIC . definition, depending on STATE, before forgetting the symbols. The This would mean switching back and implementation described here deals forth between one state which compiles with the 6502 and has to deal with the heads into the symbol dictionary the idiosyncrasy that no CFA may be and another state which compiles the located at XXFF, which in turn makes heads as usual. This switching is the definition of (CFA) and CREATE done by the variable HEADFLG (SCR somewhat mysterious! 1/23) which is respectively set and reset by DROP-HEADS and COMPILE- FORGET-SYMBOLS (SCR 1/22) is the HEADS (SCR //23). The state of word which "rolls" through every HEADFLG in turn changes the behavior dictionary and "unlinks" every defini- of CREATE (SCR 624). tion which was placed in the symbol dictionary, thereby freening it One complication is that the use (Figure 2). It is somewhat slow and of HEADFLG interferes with the it is assumed that no symbol exists symbol dictionary mechanism: If you below FENCE @ . Before forgetting are compiling into the main diction- anything in the main dictionary, ary, you want the dropped heads to be however, you must FORGET-SYMBOLS . compiled into the symbol dictionary, Otherwise links may be broken and the but if you are compiling into the interpreter won't work anymore. symbol dictionary anyway, you want the heads to go there too.

In other words, in the first case the body of a definition wou1.d be separated from the head, while in the second case, body and head would not be separated. This requires the redefinition of CREATE (SCR 624) and the use of three values for HEADFLG. The first two states are set explicitly by COMPILE-HEADS and DROP-HEADS, but the third state is recognized and handled by CREATE . When a word is compiled, its name field and link field are compiled into the symbol dictionary and the word is made immediate and (CFA) is compiled as its code field, followed by the address of the next memory location in the main dictionary. The remainder of the current definition (the body) will then be compiled into Figure 2 the main dictionary. When references

Page 148 FORTH DIMENSIONS II/5 The next step was to make the everything which had been (;CODE) had to be redefined (SCR compiled into the main dictionary, 1/25). It now uses the subdefinition including the code field, must be (;COD) and depending on the state moved into the symbol dictionary. of HEADFLG, determines the location of the code field to be rewritten and This is done by MOVE-DEF? (SCR rewrites it. #25), which is used in DOES> and ;CODE . Depending on the state of A problem might arise in the rare HEADFLG , MOVE-DEF? either compiles case where a definition whose head is (;CODE) or moves the previous defin- to be thrown away is supposed to be ition into the symbol dictionary and immediate by itself. The "solution" compiles ((;CODE)) . ((;CODE)) to this problem was to simply declare has to be one step more indirect than such a case illegal. There is a (;CODE) and resembles the function reason, however. The only situation of (CFA) in ordinary definitions. where one night want an immediate definition to be placed in the main A final note: The definitions for dictionary would be in coincidence GOT0 and LABEL, which allow multi- with [COMPILE] within some definition. ple forward references (e .g ., several Otherwise, one would want to compile GOTO's) may precede as well as follow it entirely into the symbol dictionary "their" label. Even though I imple- anyway. Such a case is so rare that men t ed this because it seemed more it did not seem worth the effort to convenient than restructuring, there redefine IMMEDIATE and [COMPILE] . is some question as to its true value To use a word whose head has been because it takes 318 bytes! compiled in to the symbol dictionary immediately within a definition, one has to use .... [ XM( ] .... ! Finally, I observed that I was generating and ;CODE constructs with big compile time definitions, which do nothing but take memory space at execution time. But dropping the heads of means that the compile time parts of these defini- Figure 3 tions won't ever be used at compile time either. Thus, if the heads of GLOSSARY are dropped, everything prior to DOES> may be TOP91 c dropped as well. It will, however, A CCNSTANT THAT LEAVES THE NEXT 3LT LAST ADORCSS TO EL USE0 AS MAIM DICTIONARY ON THE STACK. be necessary to redefine DOES> and bOTiY'4BOLS A CDNSTANT THAT LEAVES THE FIRST AOOnESS TO aE (USED ;CODE to do this (SCR C26 and SCR hS WE SYUBOL DlCTlONIRY CN THE STAX. ToPsYwaoLi - 1/27). A CONSTANT THAT LEAVES THE YEXT 311T LAST ADDRESS TO IE usfo AS swe.oL DICTIONARY ON rI(f STACK. DPSAVE A VARIABLE THA? CONTAlYS TUE 91CTIDNARY WI!ITEI OF THE At compile time, the situation of CURRENTLY INACTIVE 31CTIONARY PARIITION. TOO ( IOP-OF-OICTIONARY 1 a construct is A YARIABLE TWT COtlTAI'IS 'HE CURREVT !lEXT BIJT LAST MEUORY LJCLTION 15 aE US:' FOR :OIIPILItlC DEFI'IITIONS. '111 N-01 C as follows: While in the IjROP-HEADS RESITS 3P TO POl'li TO THE NEXT F9EE ,If!lOnY-LOCATION IN 7HE :*IN 31CTIONLRY. state, the name has been put into the I.€. THE FOLLfllllIIG DEFINITIONS ARE PERIIA>lEIITLY COIlPILED IN13 THE YAIN OICTIGNAP". symbol dictionary and subsequently !F OP HAS ALREADY POINTING INT3 TFE ;4AI!; JlC~lO!l~~v. :T DOESN'T 10,,ANYTHIWG. :DUIITTil?ARi: SYl48OL-31 C"

FORTH DIMENSIONS II/5 Page 149 3 lr 2 CLSE SV~BOL-I~:1 THE11 HEAOFLG ' 5 THEM

CUMPI Li-'IEA,lS E C3MZILE WE rEA3S ( NAME 6 LINKFIEL? I OF TME FOLLCWIUG OEFllllTIOMS INTO TIlE VAlY DICTIONAP". COUNTERPAaT: 1ROP-HEADS

3ROP.-HEADS E %E HE135 ( NUIE S LIYKFIELJ I OF 'ME FOLLOLJINI; DEFIYITICNS YILL EE COMPILED INTO THE SVIOOL 31CTlONLR". THE 4001 ( Con€- d PAPAMETERFIELD I IVTO THE IUIY 01CTIONAPV. FllRTHERHORE. THE COI4PILE Tl'C PARTS r --, OF DEFI'II7IONS IN TERHS OF (B'IILDS ... JOES) AND ... ,C?OE YILL BE COMPILED INTO TltE SV'IBOL OICTICNARY SCR 0 25 TCC., 1.f. EVERYTHING PRECEEDIpIG ... DOES) Oil J ( IEOEFtNITION OF ,CODE RESPECTIVELY WITHI11 THE :llRREtIT IEFI'IITIO'I I 1 &t PARTS nHlCH ARE LOCA'ED /,N 7<€SV'IJOL DlCTlONAl1V Z : (BUILDS HAY RE FJRGOTE4 BY I SS'JIYG FORGET-SVIIBOLS" llHl IH S CREATE SIIUOGE ; EFFtCTIVELV OISCARfJS THE HEADS I COMPILE TIME C03E. BEFCRE ISSUING "FORGET-SYMBOLS" THESE WR7S 'UV 3E !!Sf9 3OES) IN THEIR USUAI. '(ANNE9 FOR EITHE? C?l*PILATI1N lMT0 VCVE-OEF' J:O c, c mEI + a LITE?AL , ; IIIWIER LEVEL .TilNlTlOYS OR EXECUTION. ASSE'OLER DXOP UEA3S MAY NOT iO9 I'WE1)IATE *ARMING: BE VSEO PU, TAV, PLA, I( STb, INV, 0. DfFIV1-13NS. NO ERROR CHECKltlG IS *E?FO?l(EIJ ! IF, II IVC, fnm, IP 1- LJA. WA, In LOA, PHA, IP STY, /I LDA. IP 1. STA. I * LOA, CLF, Y AJC, *A, 0 * LDA, Y .* AOC, '?ISW JMP,

1 3JOO VARIABLE TOO J JUDO VAIIIABLi 3PSAVE 9 5 A : SWITCH-OIC G ;S 1 n IIERE DPSAVE DUP 3 DP I ! ; C 1 0 : ?IIAIN-OIC ( --- F-1 ) e ttmL BOTSVMBOLS w TGPSVMBOLS uEaE u( OR : F --> SCII * 23 0 ( GOTO KS ?1-1-10 scn * 21 I FORTH OEFlNlTlOYS HEX 0 ' SVHBOLDICTIONARV KS io-s-ao 1 2 DllaP-HE.(Os 3 : (GOT01 2 MAIN-OIC k DOES) OUP 1 BEGIN -0UP 3 TOPOIC TOO I ?WAIN-OIC 9. IF SWITCH-OIC THEN ; 5 WHILE DUP J SUAP s 6 HERE OVL? - SWAP I 5 SvHBoL-Ol c 7 PEP€AT,HERE OVER I 6 TOPSVIBOLS TOO ! 7WAlN-OlC IF SWITCH-DlC THEY ; 8 CFA C 0 CIA 3 3 LITERAL SillP ! ; 7 3 3 1SYHII)L I N-1 --- N-2,FLAG-1 I A : IUIVE-HEAD ( --- HERE IN VAIN-OIC-1 I 9 EOTSYMIIOLS OVER I* U( OVER TOCSYMBOLS U< At10 ; il llERE SYITCH-OIC DUP HERE 4 C OVER C3 IllOTn C1 MlN 1- 5UP )R CHOVE 0 7FENCL: ( N-: --- N-2.FLAG-1 I 0 HERE OUP 080 TOGGLE Q) ALLOT DP C1 OF9 * ALLOT C 3UP FENCE P U( ; E HERE 1 - 080 TOGGLE LATEST PFA LFA WP 3 , ! ; 3 F --> e F -> scn * 23 0 ( GOT0 IS 10-7-80 I 5 CII 22 1 COllPl LE-HEADS 0 5 VYEC LD I CT IONARV KS 10-5-80 I z : GOTO 1 FORGET-SV14SOLS S COnPlLE BRANCH -FlW9, 'IOC-LIhK 1 IF ~ROPniic CFA 2 c o CFA 1 a LITERAL - S BEGlIl ,UP d )R I - OUP >R 3 II BEGIN BEGIY 'SYYEOL tGO+ol 2. ? 1 LITERAL OVCR CFA 7' WILE PFA LFA 3 IF BEGIN OIIL 3 WILE P REPEAT 6 REPEAT JUP R) ! HERE SWAP I 0 , 7 BEGIII PFA LFA 9UP 1 ELSE II ERROR 3 *SVIlBOL SWA* 'FENCE RO C lllEN THEN 9 WHl Lf SWAP DRDP ELSE MOVE-HEAD 1 ' (GOT01 20 3 1 LlTCUL , , SItlTdI-JIC 0 A TIPEAT SWAP >R 'FEYCE THEN ; IW4fLIlATE U JtlTl L 0 --> C 3ROP ?> ERCP 9) -0UP 0- C c1 IINT: L F . ~.-IP-JlC l:TjY'*(CLZ DPSAIE I ; F --> SCII @ 2A 0 ( MTO KS 10-7-10 .) SCR # 21 1 0 ( SYWEOLOICTIONARY IS 10-5-10 I i : LABEL -FINO 1 3 IF DROP CFA OUP a L I (GOTO) :* 3 a LITETAL - 2 0 VARIABLE HEAOFLG b IF EXECUTE ELSF 4 ERROR THEN 3 5 ELSE MOVE-HEAD I 0 CFA 3 J LITERAL , , Slll'rJH-IIC. 6 THEN ; It!HEOlATE 1) : COMPILE-4EAOS *EXEC 0 HEAOFIG I : 5 I b : OROP-14EAOS ?EXEC 1 HEAWLG I i 3 FORGET-WIBOLS 1 9 ;s 8 : (CFA.) A 9 0 , 'IEi(t 0 , lWE31ATE a ( 2s - ZA TAKES 118 VTES 1 A 30~s a STATE a C 8. IF , ELSE EXEC'JTE TqEN ; D L F 0 --) E

Page 150 FORTH DIMENSIONS II/5 FORTH IN PRINT

THE TAYLOR REPORT/Alan-.-- Taylor Alternative Software RENEW NOW! Making Great St rides

Imagine i;ab,ing your c’rcn private Dimensiorts, which is iinprovinx all Cobol coml’lier -- with speclai security the tirnc. Forth for Alpha !eatc-es ar.d your user application Since Forth is extendahle -- thilt is statement. - that you could develop any user car. add new stater?t.:i!i (ei- Micro’s AMOS and keep runnlng on your future as thcr becaijse the languagc is hLt)ioiin& Hell as iur,ent hardware That would inore appreciated or else brc.a:iw the Lje a change tndeed for any user, and as particular application or ins!.ill:~:or. ! el it is sti:l ju:t a dream But there ap- wants a different vocabtildryr tht pear to be nd technical rei1so115 and few journal’s emphasis i-; or. cornraring practical reawns to eipeit that such a different methods cf :mpI~~~;mt:iip tompJer won’t bp generally available language elements. This d!t~lw5 in a ;;ear or two the community to see how to LtLF the The Forth Interest Group’s (FIG) re- language efficient. cent conference showed continued The journal also promote tht- tun- breakthroughs in really opening up tinxed development oi the Forth 3!nn- saftware capabilities to users on at dard, annual conferences, and gerieral least SIX dictinct fronts - hardware, communic~tion anlong thc rri.iny languages, environments, cross- groups. compiling. research targets and user All this, however, is only as inlpor- trainir.g. This, only a year after the tant as what IS actually m;dr wit‘i the publication of the first FIG models of FIG Forths. And that wls wh:. the the Forth language, showed how some 1960 confrreirce was particaIitr!> im- basic k.nowledge tan bear fruit. portant. The power behind these and other dwelopments has been a growing in- Outside LurguaGe trrnational group of people and firms. Forth, before now, nail an o:it-:de Headed by Chuck Moore’s own Forth, language which, wililrr soma. v$+t? t Inc., independent user groups in Pascal-like, was distinctly forb a:.is:-t!: America, Europe and Japrn who ap- and, because ot the rareiitcs ot kor!!i preciated the power of Forth have re- programmers, something thdt ust Ts sulted in small commercial ventures hated to use. with Forth compilers on micros. (The However, other more poptila. ..vd leader here, with more than 100 user coni*entiona! languages iriclud 7:. i’,i-- groups of its own, is Miller MiCrosys- cal, Lisp, Bask and (poter.tiall),t Ci:iu! terns, 1ocitc.d just a mile from can be written in Forth, thu3 reli,.i+:-.g Computerworld’s headquarters!) the rmployment problem, wh:le .d.j. From this base of people. FIG is able ing for their users the cxttntl:n,. i: ’: to produce a technical journal, Forth (Continued cn Pqc L I)

FIGFORTH, TOO If you have had a long wait for delivery of an order from the FORTH Interest Croup (again in October €3’9 “Data Files”), it may be the post office’s fault. I, too,ordered copies of the figFORTH manuals and source code for FORTH. It took 22 days for our su er-efficient postal service to deliver my copies. Also received from the FORTH Interest Group were copies of FORTH Dimensions, its bimonthly publication. The Septem- berJ’October 1980 issue, larger than normal with over 90 pages. Was professionaliy prepared and made good reading. The reason for this extra-size issue (regular issues seem to run about 35 pages) was publica- tion of the source code for entries in a “CASE” statement contest. RENEW TODAY! FORTH Dimensions is sent as part of membership in the FORTH Inter- est Group. The current membership cost is $12 per year in the US.and Canada, and $1 5 per year oversea. FORTH DIMENSIONS II/5 Page 151 MEETINGS San Diego Thursdays FIG Meeting, 12:OO HOW to form a FIG Chapter: noon. Call Guy Kelly at (714) 268-3100 1. You decide on a time and place x 4784 for site. for the first meeting in your area. (Allow about 8 weeks for Seattle steps 2 and 3.) Various times Contact Chuck Pliske or Dwight Vandenburg 2. Send to FIG in San Carlos, CA at (206) 542-8370. a meeting announcement on one side of 8-112 x 11 paper (one Potomac copy is enough). Also send Various times Contact Paul van der list of ZIP numbers that you Eijk at (703) 354-7443 want mailed to (use first three or Joel Shprentz at digits if it works for you). (703) 437-9218.

3. FIG will print, address and Texas mail to members with the ZIP'S Various times Contact Jeff Lewis at you want from San Carlos, CA. (713) 729-3320 or John Earls at (214) 661-2928 4. When you've had your first or Dwayne Gustaus at meeting with 5 or more atten- (817) 387-6976. John dees then FIG will provide you Hastings (512) 835-1918 with names in your area. You have to tell us when you have Arizona 5 or more. Various times Contact Dick Wilson at (602) 277-6611 x 3257. Northern California 4th Saturday FIG Monthly Meeting, Oregon 1:00 p.m., at Southland Various times Contact Ed Krammerer Shopping Ctr., Hayward, at (503) 644-2688. CA. FORML Workshop at 1O:OO a.m. New York Various times Contact Tom Jung at Southern California (212) 746-4062. 4th Saturday FIG Meeting, 11:OO a.m. Allstate Savings, 8800 Detroit So. Sepulveda, L.A. Various times Contact Dean Vieau at Call Phillip Wass, (313) 493-5105. (213) 649-1428. Japan FIGGRAPH Various times Contact Mr. Okada, 2/14/81 FORTH for computer President, ASR Corp. 3/14/81 graphics. 1:00 p.m. Int'l, 3-15-8, Nishi- at Stanford Medical Shimbashi Manato-ku, School, #M-112 at Palo Tokyo, Japan. Alto, CA. Need Info? I.. Pearlmutter Quebec, Canada 4 151856-123b Various times Contact Gilles Paillard (418) 871-1960. Massachusetts 3rd Wednesday MMSFORTH Users Group, Publishers Note : 7:OO p.m., Cochituate, MA. Call Dick Miller Please send notes (and reports) at (617) 653-6136 for about your meetings. site. FORTH DIMENSIONS II/5 Page 152 FORTH UlrnEflSlONS

FORTH IWTIRI8T OROUP Volume II P.O. Box 1105 Number 6 Sen Carlos, CA 94070 Price 52.00

154 Forgiving FORGET , t'l 1 * 156 Some New Editor Extensions 162 To VIEW or not to VIEW

165 SEARCH w 166 Greatest Common Divisor 168 Programming Hints

170 Development of a Dump Utility

175 Letters

178 Announcements

180 Meetings

182 FORTH Vendor List

184 FORTH, nc. News FUATH OlmEflSlUflS EDITOR'S COLUMN

Published by Forth Interest Group The theme of this month s FORTH DIMENSION IS prdctl- Volume II No 6 March April 1981 cal applications

Publisher RoyC Martens During the last two years or so I have heard from many FIG members who seem to have a common problem) No& that Guest Editor C J Street I have FORTH where do I go from here' in addition man{ of us seem to be reinventing code thdt other5 hdit. dlrLJGy Editorial Review Board running just because we are una%are of its existence

Bill Ragsdale In short FIG members dre sufferiiy froni a CJ-T'~ JV Dave Boulton problem-failure tn commcinicate Folunately this '5 a7 Kim Harris easily cured problern FORTH DIMENSIONS IS o,ir corn John James municat,ons vehicle all we have to do is use it Dave Kilbridge Henry Laxen The mechanics are simple FORTH DIMENSION5 is George Maverick seeking short universal tool type code segments for pubilca- tion If you have some code tnat VOLJ have found especial y FORTH DIMENSIONS so;icits editorial material. com- useful and can explain its funrtior arid use please conlac! ments and letters No responsibility is assumed for accuracy the editor at FORTH DIMENSIONS of material submitted ALL MATERIAL PUBLISHED BY THE FORTH INTEREST GROUP IS IN THE PUBLIC YOU DON T HAVE TO BE A WRITER' YOU will be sent d DOMAIN Information in FORTH DIMENSIONS may be publication kit that leads you through the writing procesr reproduced with credit given to the author and the Forth You will also be given all the help necessary by the FORTh Interest Group DIMENSIONS editorial staff

Subscription to FORTH DIMENSIONS is free with mem- FIG members already have a reputation as creatiJe bershipin theForth lnterestGroupat$1200peryear($24 00 problem solvers now if we will just share and exchange Our overseas air) For membership. change of address and/or to ideas. the permutations of that process boggle the mind I submit material. the address is am looking forward to enthusiastic response to this new approach that will benefit all Forth Interest Group P 0 Box 1105 C J Street San Carlos, CA 94070 PUBLISHER'S COLUMN HISTORICAL PERSPECTIVE

It's the end of the FIG year and renewals are Diling in FORTH was created by Charles H. Moore in 1969 at the (Have you renewed?) Some of our newer members might National Radio Astronomy Observatory. Charlottesville, VA be confused about renewing If you recently joined FIG It was created out of dissatisfaction with available program- and received back issues of Volume I1 of FORTH DIMEN- ming tools, especially for observatory automation. SIONS then it is time to renew for Volume Ill and your March 1981 to March 1982 membership Mr Moore and several associates formed FORTH, Inc in A number of other items of interest 1973 for the purpose of licensing and support of the FORTH FIG now has over 2800 members. worldwide Operating System and Programming Language, and to FIG will have booths at the Computer Faire, April 3-5 in supply application programming to meet customers' unique San Francisco and at the Jersey Computer Show in requirements Trenton on April 25 There are a number of new listings - see order form The Forth Interest Group is centered in Northern Caldor- at back nia Our membership is over 2,800worldwide It was formed Several reports from new chapters - lets see more in 1978 by FORTH programmers to encourage use of the Proceeding of 1980 FORML Conference is now avail- language by the interchange of ideas through seminars and able - see order form publications Looks like this is going to be our biggest year

Roy Martens

Page 153 FORTH DIMENSIONS II/6 these are the same; this test was FORGIVING FORGET thought to give some extra protection against crashing. Any vocabulary not Dave Kilbridge in CURRENT or CONTEXT may be trashed. (2) CURRENT and CONTEXT themselves point to vocabularies. If you FORGET Ac know 1edgme n t the name of the CURRENT vocabulary, or any word before it in the dic- I want to describe a FORTH system tionary, you may crash. word which has come to be known as "smart FORGET" or even "Dave The Solution Kilbridge's smart FORGET." But the ideas involved appear in the State "Smart FOKGET" overcomes these University of Utrecht, The Nether- hazards so effectively that I have lands' FORTH system at least as early never crashed by doing a FORGET. as 23 May 1970. The code presented This is made possible by linking all here is a straightforward adaptation the VOCABULARY words in the system to the FIG model. into another linked list, enabling them to be located. The head of the -The Problem list is stored in VOC-LINK. See the figure for the various fields in a The principal function of FORGET VOCABULARY word. is to reclaim memory by locating in the dictionary the next word in the How It Works input stream and resetting the dictionary pointer ( DP ) to the Refer to the code on Screen 18. beginning of the definition of that On line 7, the name-field-address of word. To avoid destroying vital the next input word is located in parts of the system, no FORGETting the dictionary; this is the point at is allowed below the address stored which the dictionary will be cut off. in FENCE. In the "dumb FORGET" of An error message issues if this the original FIG model (see Screen address is below the contents of 72), this address check is made on FENCE. This cutoff address is saved line 8. on the return stack, and the head of the vocabulary list is put on the But merely truncating the dic- parameter stack. Now everything is tionary, even at a safe place, is ready for the real work. not enough. The dictionary has a linked-list structure which allows The BEGIN ... WHILE ... REPEAT it to be searched. If a link is loop on lines 9-10 runs through all left pointing into the "never-never- VOCABULARY words above the cutoff land" beyond the new value of DP, address and unlinks each from the then the system may crash the next list. If any such vocabularies are time a dictionary search uses that found, both CONTEXT and CURRENT are link. pointed to FORTH. This removes any links described as type (2) above. These links are of two types: (1) VOCABULARY words have a link to Now the outer BEGIN ... UNTIL the latest word in the vocabulary loop on lines 11-13 runs through the they name. "Dumb FORGET" ad juste remaining VOCABULARY words. For this link (line 9) to point to the each such word, the loop on line 12 latest word which you don't FORGET, finds the highest word below the but only for the CURRENT and CONTEXT cutoff address in the corresponding vocabularies. (Line 7 verifies that vocabulary. The vocabulary head is

FORTH DIMENSIONS II/6 Page 154 then pointed to this word, thus Extensions fixing the links of type (1) above. 1. In systems which allow dynamic Finally, DP is reset to point to chaining of vocabularies, one the cutoff address (line 14). must check whether a vocabulary chained to is beyond the cutoff Improvements address. If so, it Is replaced by FORTH. (The Utrecht system Executing FORTH DEFINITIONS if does exactly that.) any VOCABULARY word is found beyond the cutoff address is unnecessarily 2. In later versions of the author's drastic. One could test CURRENT and PACE system, a base-page pointer CONTEXT and only change them if they is allocated for each new de- point beyond the cutoff, but it's fining word. These are released probably not worth the trouble. by FORGET. This is done by com- paring pointer values with the cutoff address and does not involve the vocabulary structure.

SCR # 72 0 ( ', FORGET, WFR-79APR28 ) 1 HEX 3 WIDTH ! 2:' ( FIND NEXT WORDS PFA; COMPILE IT, IF COMPILING *) 3 -FIND 01 0 ?ERROR DROP [COMPILE] LITERAL ; 4 IMMEDIATE 5 6 : FORGET ( FOLLOWING WORD FROM CURRENT VOCAIULARY *) 7 CURRENT @ CONTEXT @ - 18 ?ERROR 8 [COMPILE] ' DUP FENCE @ < 15 ?ERROR 9 DUP NFA DP ! LFA @ CURRENT @ ! ; 10 11 12 13 --> 14 15

SCR # 18 0 ( Smart FORGET DJK-WFR-79DEC02 ) 1:' ( FIND NEXT WORDS PFA; COMPILE IT, IF COMPILING *) 2 -FIND o= 0 ?ERROR DROP [COMPILE] LITERAL ; 3 IMMEDIATE 4 HEX 5 6 : FORGET ( Dave Kilbridge's Smart Forget ) 7 [COMPILE] NFA DUP FENCE @ u< 15 ?ERROR 8 >R VOC-LINK @ ( start with latest vocabulary ) 9 BEGIN R OVER u< WHILE [COMPILE] FORTH DEFINITIONS 10 @ REPEAT DUP VOC-LINK ! ( unlink from voc list ) 11 BEGIN DUP 4 - ( start with phantom nfa ) 12 BEGIN PFA LFA @ DUP R u< UNTIL 13 OVER 2 - ! @ -DUP 01 UNTIL ( end of list ? 14 R> DP ! ; --> 15 This replaces Screen 72 of the F.I.G. Model.

Page 155 FORTA DI~SIO?811/6 until you replace line 15 or enter SOME NEW EDITOR EXTENSIONS only a (CR) at the etart of a line. Then that line and any remaining ones Kim Harris are listed unchanged.

This article shows how to add 2 NEW (CR) two new commands to the FORTH editor 0 ( TEST SCREEN ) which permit the replacement or 1 old 1st line 2 2 insertion of multiple lines of a -~new text for line (CR) screen. This is a mini-application 3 something for line 3 (CR) which demonstrates string input and 4 -(CR) old 4th line output, adding new commands to the 5 'old 5th line Forth editor, manipulating vocabu- ... laries, and a "terminal input proces- sor" which prompts for input then A similar command UNDER lets you processes it. Several variations in Insert one or more lines starting at implementation are shown to illus- a specified line number. trate different styles and refine- ments. If you are only interested 2 UNDER (CR) in the final result, you can type in 0 ( TEST SCREEN ) Screen 45 (in this article) into any 1 old 1st line standard fig-FORTH system which 2 new text for line 2 already has the FIG line editor (from 3 inserted line (CR) screens 87 to 91 in the Installation 4 another inserted line (CR)

Manual). 5 -(CR)- something for line 3 6 old 4th line The use of the new commands will 7 old 5th line be illustrated by an example. Input ... is underlined; output is not. The symbol (CR) means to push the Any lines pushed off line 15 are Carriage Return key (or equivalent). lost

To begin any editing of screen Let's design this application 100 you say starting from the top. First con- sider the control flow for NEW and 100 LIST EDITOR (CR) draw a flowchart. The one below is 0 ( TEST SCREEN ) a traditional ANSI standard one. 1 old 1st line I 2 old 2nd line 3 old... 3rd line To replace one or more lines starting at line 2, say

2 NEW (CR) 0 ( TEST SCREEN ) 1 old 1st line 2-

The cursor is at the start of line 2 and waiting for you to enter new text. If you enter some text and a (CR), it will prompt you for a new line 3 and so on. This continues

FORTH DIMENSIONS II/6 This flow chart is poor. It is unstructured (i.e. , "print line" is improperly shared by two IF struc- Do tures), the loop structure requires +-- two boxes which can be performed by 1 LOOP the single word DO, and no symbol exists for the word LOOP. To program this flowchart, you either have to cheat or change the flowchart. An example of cheating is in Screen 12. This implementation of NEW is by Bill Ragsdale and works fine. The tricks are the words inside square brackets Y THEN on lines 6 and 8. These are manipu- lating the stack at compile-time, modifying the compiled branch struc- Line #=O to 15 tures. Such tricks reduce readabil- 1 prin't , line Y ity and modifiability, increase I complexity, are neither "standard" nor transportable to non-FIG enter new line? ~ystems,and are not necessary. 6read line null? A print line print line replace old line with I new one

Let's try modifying the flow- We will certainly want to use as chart to make it structured. much of the existing editor as we Repeating "print line" under the 2 can to reduce our work. The line top decision boxes makes this Replace and Insert commands are good proper. A different kind of flow- candidates: chart prevents this kind of error and is ideally suited to FORTH. It R line# - is called D-charts and was described Replace line with text from in FORTH DIMENSIONS, Vol. 1, No. 3. PAD. Not only is a D-chart inherently structured, but also there 16 a I line# - one-to-one correspondence between Insert the text from PAD at the chart symbols and FORTH words. line line#, old line line# In the D-chart of NEW, the correspon- and subsequent lines are dence between symbols and words is moved down. Line 15 is lost. as follows: We can use FORTH as a Program .L I NEII Design Language (PDL) by: needs to print the current line 1) starting with the top word number right justified in 7 (e.g., NEW or UNDER), columns followed by a space. But should the line# be passed 2) making up names for lower as a stack argument? The fol- words (i.e., forward lowing definition sets it from references), the stack:

3) and using the postfix order ; .LINE// ( line# - ) 3 .R and FORTH control structures SPACE ; but not worrying about cor- rect stack manipulation. The FORTH word I could be used before the reference to .LINE# Later the result can be finished in NEW'S definition to supply by defining all the words used, the DO-LOOP index (which is the supplying necessary stack manipula- current line number). But what tion operators, and typing them in about using I inside .LINEll's and debugging each in bottom-up definition instead? Unf or- order. tunately it's not the same. In fig-FORTH DO keeps its indices From the previous D-chart we on the return stack, so I doesn't could write the following return the index in another pseudo-definition for NEW: definition even though it was called from a DO-LOOP body. : NEW 16 0 Another word which does that is DO called I I (pronounced I prime). CR .LINE# Then .LINE# could be written: ENTER? IF ENTER NULL? IF : .LINE# ( - I' 3 .R .LINE ELSE SPACE ; (EDITOR'S) R THEN ELSE A high level definition for I' .LINE THEN is : LOOP * : I' FORTH R> R> R ROT ROT >R >R ; This incomplete definition does not take care of passing data on the (A CODE definition would be stack or switching vocabularies. preferred.) Look at the other command UNDER. The only change needed to the above Considering the inefficiency of code is to use the EDITOR'S I I' and readability, let's pass instead of R. Because the two the line number on the stack. definitions are so similar, we will want to share some of the common The next choice is should we use parts. a separate definition for .LINE# (as above) or copy the contents To finish the definition of NEW, of its definition into NEW. Exe- let's consider each undefined word. cution speed would be indistin- guishable. Using the name .LINE#

FORTH DIMENSIONS II/6 Page 158 migh be more readable, but not Passing I on the stack would much. The dictionary sizes are make ENTER? look like: different for the two choices. (Sizes are in bytes.) : ENTER? (start-line# current-line#-) OVER = ; .LINE# separate included in NEW 6 UNDER

literal 3 4 2x4=8 .R SPACE 4 2x4=8 .LINE# head 5 + name size= 10 9 2 references 2x23 4

So for only 2 references to But more words are needed in .LINE#, it doesn't pay to define NEW's definition to complete the it separately. (3 references enter-mode control. As with would make it close: 24 to 26 .LINE# before, the contents of bytes .) ENTER? could be copfed in NEW's definition instead of being ENTER? defined separately. The size tradeoffs would favor that, but This should be true: in this case readability would be greatly enhanced by keeping 1) when the current line # the name. This also eliminates equals the starting line # the need to comment each part of that IF structure (as in the 2) while new text is being version on Screen 12). entered ENTER 3) but not after a (CR) only has been entered. must wait for terminate input, then copy the entire line to PAD We never want to use a VARIABLE for later use by the editor. for temporary storage if we can help it. The starting line QUERY reads a line of input, and number comes in from the stack, TEXT can copy it to PAD: so (1) is simple TEXT c - start-line# I = Copy text from the Terminal Input Buffer (The argument must be preserved to PAD until the each iteration, so a DUP must be delimiter c is found. added; a DROP will have to follow LOOP to compensate.) Case (2) So we could define ENTER with: can be achieved by incrementing the start-line# while in enter- : ENTER ( - ) mode. This can be done with a QUERY 1 TEXT ; 1+ after the Editor's R. Finally (3) falls out by not incrementing it after either .LINE in NEW'S definition.

he159 FORTE DIMENSIONS 11/6 NULL? The only rm;ning ;/21=ge~ -* needed concerns rocabulrricr- a- should be true only if a (CR) add these definitions to tL Lwm was ENTERed. fig-FORTH puts a vocabulary, use the phrase null character (i.e., binary zero byte) in the Terminal Input EDITOR DEFIW1TIO.S Buffer (TIB) when a (CR) is entered. To tell if it is at before the first deflnitiim, d tLr the start of the buffer, we can phrase use: FORTH DEFINITIONS : NULL? ( - f ) TIB @ C@ 01 ; after the last. But within m's definition we need to specify which Although keeping this definition I and R are intended. FORTH uses separate would take up more pairs of names to resolve such space than using its contents ambiguities. It's like last names inside NEW and UNDER, readabil- in people's proper names: ity is improved, so we'll keep it. JOHN DOE

Finally, .LINE JOHN DEERE

needs a screen number and line But in good postfix style, the number. The line number can be vocabulary name must precede the supplied by the DO-LOOP index. word it applies to, and remains in So before each .LINE in NEW or effect until changed. Vocabulary UNDER add: names in fig-FORTH are IMMEDIATE, so they can be used inside definitions I SCR @ .LINE the same way as outside. Within NEW'S definition, we need to insert Incorporating all the above FORTH before DO to make sure all the refinements into the previous 1's are DO-LOOP words and not editor pseudo-definition of NEW produces words. the following code:

: ENTER? ( atart-line# current-line# - f ) OVER - : :ENTER (-) QUERY 1l"T :

: NULL? ( - f ) TIB e ce 0- ; : ( atart-line# - ) 16 0 DO CR I 3 .a SPACE I ENTER? IF ENTER NULL? IF I SQ e .LINE ELSE

I ( EDIIOP'a ) R 1+ TEEN ELSE

I SCR @ .LINE THEN LOOP

DROP :

FORTH DIMENSIONS 11/6 Page 160 NEW PRODUCT Also we need to put EDITOR before the R (the editor's Replace command), and FORTH after R to make the HOME GROWN APPLE I1 SYSTEM: remaining 1's be DO-LOOP words. As an avid FORTH user, I would Adding the vocabulary names like to share my work with other makes the previous definitions Apple I1 users. Assembling the testable. Trying them reveals that fig-FORTH model source code on CP/M it all works except the line printed and other systems with assembly after the (CR) only was entered language development tools is rela- (i.e., leaving enter-mode) has one tively straight forward, but for the additional space before it. This primarily turn-key Apple a lot of skews that line from all the others. additional, undocumented information This is because fig-FORTH echos a is required. To equalize this space when the (CR) is entered. To situation I will supply my home fix this ugliness, back up the cursor grown Apple I1 system on disk to 1 column before printing that line. anyone for $30.00. No documenta- For most terminals, a Back Space tion, support, or instruction is character will do the trick. (Not provided save for technical notes on so on a memory-mapped terminal.) the disk supplementing the FIG Defining the following will output a installation manual. An assembler, Back Space: screen editor, source code and asso- ciated compiler are included. The : .BS ( - ) 8 EMIT' ; idea is to be able to upgrade and patch the system in various ways It should be inserted after the from listings (standards, any- phrase NULL? IF in NEW'S definition. one?). Not for beginners, not a Because this function is terminal- commercial product, at your own dependent, it definitely should be a risk. Contact George Lyons, 280 separate definition. Henderson St.; Jersey City, NJ 07302

The final working version follows :

SCR # 45 0 ( EDITOR EXTENSIONS: NEW UNDER KRH 9FEB81 ) 1 EDITOR DEFINITIONS 2 : ENTER? ( start-line# current-line# - f ) OVER = ; 3 : ENTER ( - ) QUERY 1 TEXT ; 4 : NULL? ( - f ) TIB @ C@ 0s ; 5 : .BS ( - ) 8 EMIT ; 6 7 : NEW ( start-line# - ) FORTH 16 0 DO CR I 3 .R SPACE 8 I ENTER? IF ENTER NUL? IF .BS I SCR @ .LINE ELSE 9 I EDITOR R FORTH 1+ THEN ELSE I SCR @ .LINE 10 THEN LOOP DROP ; 11 : UNDER ( start-line# - ) FORTH 1+ 16 0 DO CR I 3 .R SPACE 12 I ENTER? IF ENTER NULL? IF .BS I SCR @ .LINE ELSE 13 I EDITOR I FORTH 1+ THEN ELSE I SCR @ .LINE 14 THEN LOOP DROP ; 15 FORTH DEFINITIONS takes less than 170 bytes c~r av system. The compiling overhead is TO VIEW OR NOT TO VIEW just as small. Only one or two bytes per definition and a negligible (TO VIEW OR TO VIEW NOT?) addition to compile time. Verv inexpensive for the convenience and George William Shaw I1 power it gives.

Sometime back, about one year In order for VIEW to work, some ago, a fig-FORTH package was distri- of the resident defining words must buted to the members at the monthly be redefined. In pre-compiled fig- FIG meeting. One of the programs in FORTH systems, the defining words the package was a command called CONSTANT, VARIABLE, VOCABULARY, : VIEW. This command would allow you (colon), and DOC<. >DOC< will store in memory screen by simply typing VIEW, fol- the disk screen number which con- lowed by the name of the command you tains the source of the definition wish to see the source text of. being compiled. (On systems which can recompile themselves, >DOC< need I have been asked by Carl Street, not be placed in each one of the the guest editor for this issue of defining words. It need only be Forth Dimensions, to write a commen- placed in the word CREATE, which is tary on this command which is to used by each of the defining words describe how the code originally to enter a definition into the submitted in the goodies package dictionary .) works and what other additions or changes I would make to the code. With >DOC< in either CREATE or each of the defining words, the disk So why have VIEW? VIEW adds screen number which contains the convenience to writing and editing source will be stored in memory to programs. The command allows you to allow later referencing by the get directly back to the source command VIEW. The command VIEW, screen of a compiled definition, then, has the task of finding the rather than trying to remember just requested definition in the dic- what screen it was an. Most of us tionary, fetching the screen number can remember approximately what from memory, and listing the screen. screen or screens we have been This entire procedure is quite working on, but if we have been simple in FORTH and can be accom- working with more than a few screens, plished in a single line of source we would usually have to list a code (excluding the comment): couple of screens to find the source to review or edit a given defini- tion. VIEW eliminates this problem by allowing us to reference the source on the disk by the name of The word [COMPILE] causes the

the compiled definition. 1 word ' (tick) to be compiled into memory, rather than being executed VIEW also takes very little at compile time (' is immediate). system overhead. The entire com- When VIEW is later executed I will piled source for VIEW with all search the dictionary for the name extensions mentioned in this article which follows VIEW. NFA takes the

FORT% DIMENSIONS II/6 Page 162 address left on the stack by ' (the time rather than being compiled as parameter field address) and changes desired. The other words are riot it to the Name Field Address. 1 - immediate and would not have this then gives the address of the byte problem. immediately preceding the name field. C@ extracts the screen number (which Now, when any one of the defining was stored at compile time) where words executes, >DOC< is executed, the source of the definition is storing the screen number being located. LIST prints the source of compiled immediately preceding the the definition. The second [COMPILE] name field of the definition. The allows EDITOR to be compiled (EDITOR area immediately preceding the name is immediate) to select the editor field was selected because this area vocabulary when VIEW is executed. can be addressed directly with This last step allows convenient existing FORTH words. The parameter entry into the editor for editing if field area of FORTH words is of vari- desired. able length, so the area immediately following the end of the definition : >DOC< BLK @ B/SCR / C, ; would not be as easily addressed.

>DOC< stores a one byte screen When it is desired to VIEW a number in memory of the screen from viercompiled word, the source screen which source text is currently being number can easily be accessed and interpreted or compiled. BLK con- the definition listed. If a word tains the block number as above. In which has not been compiled with the fig-FORTH, the block number and the screen number preceding it is VIEWed, screen number may not be the same the screen determined by whatever (there may be several blocks per byte immediately precedes the defini- screen), so a division is performed tion will be listed. with B/SCR (blocks per screen) to obtain the screen number. If in The current definition of VIEW your system B/SCR is one (11, YOU works great except for a few minor may eliminate the division by B/SCR idiosyncrasies. First, only a single and additionally speed the execution byte is stored in memory for the of >DOC<. source screen number. If you have screens above 255 and compile from . CbNSTANT >MC< iCOWILL! COIISIAtiT , : VARIABLE >DOC< [COWILEl VALIMLL , them, the source cannot be viewed : VOCMbLABY )DOC< [COWILL] VOCABLUY ; .. >DOC< (COPWILE] : directly. A larger number is then . wc< [CoPWlLr! (ICIIDS ; needed. By simply changing the C, and C@ to , and @ in >DOC< and VIEW >DOC< is then placed immediately respectively, any screen currently preceding each defining word to accessible by the FORTH system could store into memory the screen number be VIEWed. Note that the address currently being interpreted. Since calculation must also be changed for most of us our fig-FORTH is from 1 - to 2 - to account for the pre-compiled (we can't recompile the additional byte, as shown below: basic FORTH system), each defining word is simply redefined to be preceded by >DOC<. The [COMPILE] in each of the words is actually only necessary in the redefinition of : (colon) because it is immediate and would attempt to execute at compile

Page 163 FORTH DTMENSIOffS tI/6 Also, to the list of words being redefined I would add USER, CODE and FIGURE 6 CREATE. Redefining USER will allow the location of the definition of Note that if the test for block the user variable. Redefining CODE zero (0) is placed in >DOC<, then will allow the VIEWing of words VIEW will try to list those defini- defined in assembler. Redefining tions which would have had a screen CREATE will cause all defining words number of zero (0) with the same 2 at er compiled to bui Id VIEWable result as attempting to VIEW a (vords. definition which was not defined with the redefined defining words. : USER >DOC< USER ; : CODE >DOC< CODE ; George W. Shaw I1 : CREATE >DOC< CREATE ; SHAW LABS, LTD. P.O. Box 3471 It should be noted also that if Hayward, CA 94540 you have changed the structure of your dictionary by placing links first (as I have) that the address NEW PRODUCT calculation in VXEW will have to be changed as below: FORTH-79 FOR APPLE:

MicroMotion has announced the release of FORTH-79 for the Apple The additional 2 - (to 4 - ) is computer. MicroMotion FORTH-79 is a necessary to skip the link which structured language that is claimed precedes (rather than follows) the to conform to the new FORTH-79 name field in these systems. International Standard. MicroMotion FORTH-79 :omes with a screen editor And lastly, the current defini- and macro-assembler. Vocabularies tion of VIEW will even try to list are included for strings, double LORES the source screen for definitions precision integers, graphics which have been created at the key- and modem communication. Its board. The block number stored for operating system allows multiple these definitions is zero (0), which disk drives and is 13 or 16 sector is not where the source is at all. disk compatable. MicroMotion If you don't mind having block zero FORTH-79 runs on a 48K Apple I1 or (0) listed when you request to VIEW Apple I1 Plus. Retail price is a definition which you created at $89.95 including a professionally the keyboard, then there is no written tutorial and user's guide problem. But, if this does bother designed to make learning FORTH-79 you, you can put in the test below: easy for the beginner. MicroMotion; 12077 Wilshire Blvd., Suite 506; Los Angeles, CA 90025; (213) 821-4340

(Editor's note -- The manual is excellent. It notes the differences In addition to the above, a test between fig-FORTH and FORTH-79 where may be put in >DOC< to prevent the pertinent) storing of the screen number when compiling from the keyboard:

RENEW TODAY!

FORTH DIMENSIONS II/6 Page 164' screen. Then when you need to SEARCH search, load the screen. (Of course if you are using a proprietary John S. James version of FORTH, it may have an editor and search function built in and automatically available when When you are debugging or needed. This article-ette is mainly modifying a prcgram, it is often for FORTH users whose systems are important to search the whole program the ten-dollar type-it-in-yourself text, or a range of it, for a given variety .) string (e.g., an operation name). The 'SEARCH' operation given below Here is an example of using does this. 'SEARCH'. We are searching for tiit string 'COUNT' in screens 39-41; the To use 'SEARCH', you need to source code of 'SEARCH' is on screen have the FIG editor running al- 40. The screen and line numbers arc ready. This is because 'SEARCH' uses shown for each hit. Incidentally, some of the editor operations in its the search string may contain blanks. om definition. The 'SEARCH' source Just type the first screen number, code fits easily into a single the last screen number, SEARCH fol- screen; it is so short because it lowed by one blank and the target uses the already-defined editing text string. Conclude the line with functions. Incidentally, the FIG return. ~ The routine will scan over editor is documented and listed in the range of screens doing a text the back of FIG'S Installation match for the target string. All Manual. matches will be listed with the line number and screen number. Use the editor to store the source code of 'SEARCH' onto a Happy SEARCHing !

Example of Use:

39 41 SEARCH COUNT 00 VARIABLE COUNT- ER 2 40 1 COUNT ER +! COlTNTER @ 4 40 1 COUNTER +! COUNT ER @ 4 40 56 > IF o COUNT- ER-! 5 40 12 EMIT 01 TEXT 0 COUNT- ER ! 8 40 OK

CORRECTION:

CROMEMCO DISKETTES described on page 145 of Vol. 11/5 are supplied AREYOUA-- --- FIGGER? by : YOU CAN BE! Inner Access Corp. RENEW TODAY! PO Box 888 Belmont, CA 94002 (415) 591-8295 On Screen 20, wt' see a version of the greatest common divisor GREATEST COMMON DIVISOR routine called G-C-D written in fig- FORTH. Line 1 begins a colon Robert L. Smith definition. In lines 2 and 3 the two arguments at the top of the stack are conditionally swapped to The problem of finding the force the larger of the two arguments greatest common divisor (GCD) of two to be the first dividend. This step integers was solved by Euclid more is used to avoid an unnecessary than 2200 years ago at the great division in the succeeding part. library in Alexandria. The technique However, lines 2 and 3 can be omitted is known to this day as Euclid's entirely with no effect on the Algorithm. The method is essentially answer. The body of the calculation an iteration of division of a prior is in lines 4-7. At the start of divisor by a prior remainder to yield the BECIN-WHILE-REPEAT loop, the top a new remainder. The quotients gen- element of the stack is the prior erated by this process are useful in divisor and the second element is other applications, such as rational the prior remainder. In line 4 the fraction approximations, but are not new divisor (prior remainder) is required for finding the greatest saved, and the order of the top two common divisor. elements reversed to prepare for the division. In line 5 the division For readers unfamiliar with the with remainder is performed, and the process, an example should clarify remainder copied to the top of the the method. Suppose we wish to find stack for testing in line 6. For the GCD of 24960 and 25987. Divide cases of non-zero remainders, the one number into the other, and find quotient is discarded but the remain- the remainder or modulus: der is kept in preparation for the next stage in the loop. The process 25987 24960 MOD -> 1027 terminates with a zero remainder. At line 8 the final quotient and Divide the previous divisor 24960 by remainder are dropped to yield the the remainder 1027 to yield: preceding remainder, which is the desired answer. Finally, the answer 24960 1027 MOD -> 312 is printed out. The semicolon at the end of line 8 terminates the Continue the process as follows: definition.

1027 312 MOD -> 91 When Screen 20 is loaded, lines 9-11 are executed to print an invi- 312 91 MOD -> 39 tation to the user to try the routine. 91 39 MOD -> 13 There are three areas in which 39 13 MOD -> 0 this routine can be improved. The first is to remove lines 2 and 3 The last non-zero remainder is entirely, since the code does not our desired answer, 13. This process usefully contribute to the final must converge since the remainder is result. Furthermore, there is always less than the divisor. The probably not even a speed advantage process will terminate for finite for machines with a hardware divide. numbers and integer division. Secondly, since the quotient is not used, the /MOD function can be re- The sequence in GCD is quite placed by the MOD function with a easy to follow now. The two argu- little reworking of the code. ments on the stack are swapped, and Finally, the printout function can the 2nd element is copied over the be separated from the calculation first, in preparation for the function. It is usually advanta- division implied by the MOD function. geous in FORTH to write each defini- The word ?DUP is the 79-Standard tion so that it does as little as version of the fig-FORTH word -DUP. possible! The advantage of the The function of ?DUP is to duplicate separation in this case is that the the top element of the stack (the calculation function can be applied remainder from the division in this repeatedly for finding the greatest case), but only if the remainder is cornon divisor of more than two non-zero. The function O= reverses arguments. the logical value of the top stack element, so that the test in UNTIL Our modified screen is shown will cause a branch back to the BEGIN be low: part when the MOD function results in a non-zero value. When the re- : GCD mainder is zero, the zero value is BEGIN not duplicated. Instead, the O= SWAP OVER MOD ?DUP 01 function converts it to a 1, which UNTIL in turn is dropped by the action of UNTIL. Furthermore, control is then passed from the BEGIN-END loop, and : G-C-D the function terminates, leaving GCD CR ." The G-C-D is " . only the previous non-zero remainder. , Note that the number of FORTH CR ." Input two numbers, then" words in the basic definition has CR ." execute 'G-C-D'. The" been effectively cut in half, com- CR ." greatest common divisor" pared to the original version in CR ." of these numbers will be" Screen 20. CR ." displayed." CR The author gratefully acknow- ledges discussions with LaFarr Stuart in the preparation of this article.

SCR # 0 ( Greatest common divisor, a demo WFR-79DEC09 ) 1 : G-C-D 2 OVER OVER < 3 IF SWAP THEN ( use larger as quotient ) 4 BEGIN SWAP OVER ( save divisor third ) 5 /HOD OVER ( test remainder zero ) 6 WHILE ( not zero ) DROP ( this dividend ) 7 REPEAT 8 DROP DROP CR ."The G-C-D is *' . ; 9 CR ." Input two numbers, then execute 'G-C-D'. The greatest" 10 ." common divisor of these numbers will be displayed." 11 CR 12 13 14 ;S 15

Page 167 FORTH DIMENSIONS 11/6 PROGRAMMING HINTS address aiid lllci.t\ 11 0.1 ttlr. p.ir.1 meter stack. Now the ] places us back into compilation mode. The value we have thus computed, namely >.Tr i; \dve iurrent DP on retux stack .- the runtime address of : , is then .. -F\ ! I LiTEMi , i :e: runtime :Jr s7 ' :ecuritv, stilrt :ompiling compiled as a literal in the defini- ~ 3EC;!t :: . :: ' :!.:ERF'R!: Compile bhat is tvped tion for When is exe- - iTATE ' -H!ii ( i'ntl! 5tate changes cuted, this literal is compiled '9 .:'ER1 Get another line from TTY i TEPF.4: inline by the , that follows. This 2

: h -Xfi.? ~ \ow do u5at ~se:wanted . ? :r ' , i ind resture dictionarv nition, so that it will execute ...- ._ properly when the time comes. .._- 3 !CSP ] :: is an excellent example of the flexibility of FORTH. Certain The !CSP is used for compile constructs in FORTH cannot be typed time error checking. The check is in from the terminal unless the user made when the user types ; to end is in compilation mode. These con- his definition. The ] puts the structs include: DO, LOOP, IF, ELSE, user into the compile state. What THEN, and all of the conditional is typed from now on will be compiled compiling words. However, :: allows instead of interpreted. you to do this if you so desire. The idea is simple enough; you create 4 BEGIN an "orphan" word in the dictionary, execute it, and then forget it. (An This denotes the beginning of orphan is a definition without a name some kind of looping structure. header). 5 INTERE'RET Let's step through the above defini- tion line by line and see what is This is the main word in FORTH. happening at each point: It either executes or compiles the words it encounters depending on the 1 HERE >R current state. In our case it is compiling the words it encounters. HERE is the location of the next available dictionary entry. 6 STATE @ WHILE This location is saved on the return stack so it can be restored later. STATE is the variable which determines whether one is inter- 2 [ ' QUIT CFA @ ] LITERAL , preting or compiling. When it is non-zero one is compiling, hence the [ changes from compilation mode loop is repeated as long as the user to interpretation mode. QUIT has is still compiling. When you type been previously defined as a high ; STATE is set to zero, and this level : definition, and hence we loop is exited. use ' QUIT to get the address of its PFA. The CFA then converts 7 CR QUERY this PFA to the CFA for QUIT. Since QUIT is a : definition, This simply gets another line this CFA points to the runtime from the terminal so that INTERPRET for : , which controls the nesting can compile it. level in FORTH. The @ gets this

FORTH DIMENSIONS II/6 Page 168 8 REPEAT NEW PRODUCTS

This is the end of the BEGIN loop. CROSS-COMP1 LLR I'RO(.KAM :

9 SWDCE Nautilus Systt.ms iiow dffcrs .i cross-compiler prograin tor FORTH SMUDGE is used to undo the users. %chin? reari,+hle ~7c:rsic~ns SMUDGE present inside of ; . It are fiow ;i:~di1ilhlt~ lor t t.!(> toll ow in^ has no other purpose in this context. hardware systems: LS 1 - 1 ! , C!);P1, TRS-80, Apple, H-83, ,ind X,.)rthsL

This article contributed by Henry Timin Engineering is now oiltar- Laxen; 1259 Cornell; Berkeley, CA ing a version of figFORTH for 808oq/ 94706 8085/2-80 or CDOS systems witti at least 24K of memory. The Timin syscem features a FORTH styie editor with NEW PRODUCT 20 commands, a virtual memory sub- system for disk I/O, a 2-80/8080 GO-FORTH FOR THE APPLE 11: assembler, and an interleaved disk format to minimize disk access The CAI FORTH Instruction System time . Documentation includes a by Don Colburn is now available for manual that may be purchased the Apple. The GO-FORTH CAI System separately for $20 (credited towdrds takes the novice FORTH programmer purchase of disk). Price $95.0C on through the pitfalls of learning IBM compatible 8 inch single density FORTH and lets him fly. Requires disk (other disk formats $110) -- 48K Apple I1 plus Apple disc. Price California residents please add 6%. is $45.00 per system (1-3 units), sales tax. -- and includes shipping $30.00 per system (more than 4 by mail in U.S. Mitchell E. Timin units). International Computers; Engineering Company; 9575 Genesee 110 McGregor Avenue; Mt. Arlington, Avenue, Suite E-2; San Diego, CA NJ 07856; (201) 663-1580 (evenings). 92121; (714) 455-9008

Page 169 FORTH DIMENSIONS II/6 DEVELOPMENT OF A DUMP UTILITY

(DEVELOPMENT OF A DUMP UTILITY By John Bumgarner March 81 ) Cli 0'h i (DLXP MEMORY BYTES. ADDRESS COUNT. . . 1 OK !7 h: 2 : i)LT1P 0 DO DUP I + C@ 3 .R LOOP DROP ; OK OK 3 HEX OK 4 1 2 3 HERE 10 DUMP CR . . . 4 44 55 4D 50 20 20 20 20 20 20 20 20 20 20 20 5 321 OK OK b ( Test for non-printing ASCII Character. CH .. . T/F) OK OK 7 : ?NON-PRINTING DUP 20 < SWAP 7E > OR ; OK 8 : Q ?NON-PRINTING . ; OK 9 -1OQOQlOQ 1FQ 2OQ 40Q111100 OK lo 7E Q 7F Q 100 Q 7FFF Q 8000 Q 0 1 1 1 1 OK 11 FORGET Q OK OK OK 12 ( Type any memory bytes using . for non-printing characters) OK 13 ( Address Count ...) OK OK lb : &TYPE 0 DO DUP I + C@ DUP ?NON-PRINTING IF DROP 2E ( .) THEN EMIT LOOP DROP ; OK OK 15 1 2 3 HERE 10 &TYPE CR . . . .6TYPE 16 3 2 1 OK OK OK 17 (Print address , DUMP &TYPE 16 bytes. Address ... ) OK OK 18 : A-LINE CR DUP 0 6 D.R SPACE 10 OVER OVER DUMP 2 SPACES &TYPE ; OK OK 19 HERE A-LINE, 2419 6 41 2D 4C 49 4E 45 20 20 20 20 20 20 20 20 20 .A-LINE OK OK OK 20 2 3 4 HERE A-LINE CR . . . 2419 6 41 2D 4C 49 4E 45 20 20 20 20 20 20 20 20 20 .A-LINE 432 OK OK OK 21 (Can't think of a better name. Address count ... ) OK OK 22 : DUMP 0 DO DUP I + A-LINE 10 +LOOP DROP ; DUMP isn't unique OK OK 23 HERE 40 DUMP 243A 4 44 55 4D 50 20 20 20 20 20 20 20 20 20 20 20 .DUMP 244A 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 245A 20 20 32 84 44 55 4D DO 5F 5F 5F 5F 5F 5F 5F F5 2.DUM. - - 246A 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5F 5P 5F 5F - - OK OK OK

FORTH DIMENSIONS II/6 Page 170 Program development in FORTH can The inside oi the loop first --and should--be done in a "top down" duplicates the address (the only manner as this type of design pro- thing remainicg on the stack after duces error free programs in a DO removed its two arguments) to minimum of time. However, the road save a copy and then ddds the loop to a solution is not always direct; index to it. Using this new address and experienced FORTH programmers we fetch a byte with CE and print often play with a programming problem it, right justified in a '3 column on the terminal to get ideas. These field using 3 .R , In the saint' idea sessions usually result in the manner we keep looping (incrernenting data necessary for "top down" program the index by 1 each timc) adding, design. The development steps in- fetching and printing. When the loop volved in producing a really useful index equals the count, the ioop tool from a very simple DUMP word exits and drops the extra copy of the will illustrate just such a design address to clean up the parampter session. stack--A very important step!

I begin by setting down in the FORTH is highly interactive and comment on line 1 the functions and nothing is more natural than LO test parameters for the fundamental DUMP the new DLWP word immediately. In word to be defined -- I simply want line 3 I switch to hexadecimal I/O it to dump values from memory. Given to enable easy interpretation of the the starting address and number of dump results in line 4. Before I bytes to dump as parameters on the actually execute DUMP in line 4 I stack, the word defined in line 2 is put a few numbers on the stack so short and simple. The count. value that I can check to see that the is on top of the stack which suggests stack is not altered by DLJMP . using a DO ... LOOP to do the work. The word HERE provides a starting Inside the loop we put the code to address for DUMP and then I select generate an address, fetch and print 10 (in decimal, 10 hex is 16) bytes a byte. The loop parameters are the to dump. The CR . . . after DUMP count value on the stack and the zero prints (on a new line) and removes put inside the definition just in the top three numbers of the stack. front of the DO. Lines 4 and 5 show the execution of the word and also show my check FORTH DO loops increment the loop numbers are where they should be. index and check it against the limit This simple check shows that DUMP at the end of the loop. If the newly is very likely to be free of errors incremented index is less than the and we may proceed with confidence. limit, the loop body is executed again. If the index is greater than I happen to like dumps that dump the limit, the loop is terminated both byte values and ASCII char- and execution continues with the acters and so my next task was to next word. This method of loop make a word that could dump in ASCII control results in the loop index what DUMP output as numbers. I (fetched for use by the word I ) have also learned from frustating going from 0 to count 1- (that is experience that printers and termi- Count-1 for non-FORTH persons) by nals should not be given byte values 1's for this FORTH DUMP word. The that are non-printing characters loop index then is just what we need lest they do some strange things in to add to the starting address to response. By thinking ahead a obtain successive byte addresses for little bit I can see a definite need dumping. for a word to alter the memory byte

Page 171 FORTH DIMENSIONS II/6 vdlues to an acceptable range for On lines 12 and 13 1 put down my the output device. The result of ideas for the word which will type this advanced thinking is shown on the ASCII character equivalents for !iries 6 and 7. Given a character my memory byte values and begin the ~~alueon the stack ?NON-PRINTING definition on line 14. This defini- Kill return a True (plus one) value tion is just like the one for DUMP if it is a non-printing character except for what happens to the byte and an False (zero) otherwise. The value after it is fetched. In place test is made for values less than of the 3 .R of DUMP we check for hex 20 (a space) and greater than non-pr i n t ing charac t er s with ? NON- hex 7E (a tilde). PRINTING and if they are non- printing we DROP the value and At this point I am still in hex replace it with the hex code for a for numeric I/O (see line 3) and so dot, 2E. Then we EMIT the byte to I use 20 and 7E directly in the see the ASCII character for that definition without having to look up byte's value. their equivalent decimal values. The OR at the end of ?NON-PRINTING Some programmers will want to combines the results of the two mask the byte value with hex 7F to limit checks and produces a single zero the high bit before testing for true/false value for the output if non-printing characters. One reason either limit is exceeded. to do this is so fig-FORTH names will show up better in dumps since The verification of a limit the "traverse" bit on the last kept checking word like ?NON-PRINTING name character would otherwise turn requires careful testing with data that character into a non-printing that exercises the word over its value and it would appear as a dot. entire range and especially at My reason for not doing it is that critical places such as the limits. getting rid of the high bit turns With ? NON-PRINTING this means too much data into ASCII and clutters testing 10 or more times with care- ~p that part of the dump. The fully chosen input values. The name testing of &TYPE is done exactly of ?NON-PRINTING is nice and des- like the testing for DUMP , the criptive but is too long for a poor .&TYPE after the CR . . . is the typist like me to type often so on output of &TYPE . The dot before line 8 I have defined the word Q the ampersand is the count byte of to execute ?NON-PRINTING and print the string getting turned into a dot the result. On lines 9 and 10 I try by ?NON-PRINTING . my new Q word out with some numbers designed to make it fail if it will. Incidentally, the string found Numbers such as small negatives, at HERE when a given word is zero, small positives, on either executing in the interpretive mode side of the lower limit, mid range, (outer or name interpreter in this either side of the upper limit, case) is the name of the word. Look larger positives and at the magic up the ASCII characters for the byte place where the sign bit changes values dumped in line 4 and you will value. The results show that ?NON- find they spell DUMP . This bit PRINTING is not fooled by these of magic is performed by the word tests and so on line 11 I discard my WORD in figFORTH. test word Q .

FORTH DIMENSIONS II/6 Page 172 With the two words DUMP and for our two words DUMP and &TYPE &TYPE we are in a good position to . I put 2 spaces in to separate the write a word that will dump one line byte values from the ASCII of information on the terminal. characters. This word can then be executed in a loop, once for each line dumped. I On lines 19 and 20 of tlir print- call this word A-LINE and define out I test A-LIKE: for st,ick it in line 18 after noting in line problems and func t iona I i ty ,ind i c 17 that it should print the starting seems that everything I5 barkir~g address of the dumped line. P. normal correctly. line width on a CRT type terminal is 80 columns and so there is room for At last I am now re

Page 173 FORTH DIMENSIONS rIr6 The actual definition of the to the limit of disk storage on all new DUMP is very similar to the disks; Case statements; Printer old DL'MP except that we are sub- support using MDOS ASSIGN statc- stituting A-LINE for the C@ 3 .R ments; Forgetting across vocabulary arid since we are dumping 16 bytes on boundaries; Enhanced disk procedures a line we dse +LOOP to terminate that reduce response time, compiling the CO and give it a 16 (10 hex) time, d number of disk accesses; to add onto the loop index each Physical disk support for disk time. Now the address computation diagnostics and disk copy and direct done hy the DUP I + phrase will access to MDOS file directory. start aL the specified point and go Acropolis A-FORTH has an 89 page up by lh bytes each time through the users manual. Acropolis provides loop a A-FORTH updates 6 patches at no charge for 1 year after purchase. The useful tool that I set out Price $150.00 including shipping to develop at the start of this (California residents add 6% sales session is now complete and only tax). Acropolis division Shaw Labs, needs to be tested. Line 23 does Ltd.; 17453 Via Valencia; P.O. Box this final test, but because of my 3471; 'Hayward, CA 94540; (415) 2 76-6050 earlier successful test of A-LINE ______c and also because the new DUMP is NEW PRODUCT so similar to the old DUMP I did ALPHA MICRO REENTRANT FORTH: not bother to try putting some numbers on the stack to see if it Sierra Computer Company is now adds or removes any values. I now offering version B of their AM-FORTH have high confidence that DUMP for Alpha Micro system AM-100 compu- will work correctly and it does. ters. Version B is said to be re- entrant, allowing the basic FORTH This article contributed by John dictionary to be loaded as part of Bumgarner; FORWARD TECHNOLOGY; 1440 the AMOS system and shared by any Koll Circle, Suite 105; San Jose, number of users in the multi-user CA 95112 Alpha Micro system. Other new features include: An assembler; Screen oriented editor; Support of NEW PRODUCT special AMOS CRT handling features; Floating point math operations; MICROPOLIS FORTH: Utilities for string handling and building data structures and access Acropolis now offers FORTH for to system TIME and DATE functions; Micropolis. Acropolis FORTH More versatile 1/0 to AMOS sequen- (A-FORTH) runs under Micropolis MDOS tial and RANDOM files; and use of on 8080/8085 and 2-80 systems running lower case characters. All features at 2 or 4 MHz with 32K memory and at of version A are included in version least one MOD I or MOD I1 disk. B. AM-FORTH version B is available A-FORTH has 2 program/data file on AMS or STD disk that contains editors -- a line editor for standard complete source code; executable serial terminals and a screen editor object code; FORTH utilities for the for memory-mapped terminals. A-FORTH editor, assembler and data struc- has an 8080/8085 macro-assembler that tures and some sample FORTH programs. allows use of any mixture of A-FORTH Complete documentaton describing and assembly code desired in a single AM-FORTH implementation, installa- definition. A-FORTH has all the tion procedures, operating instruc- features of figFORTH plus: Double tions and glossary. Price is $150.00 precision math d stack operations ($120.00 to licensed version A (32 bit); Double precision variables purchasers at $40.00). Contact George & constants (32 bit); Multi dimen- Young; Sierra Computer Company; 617 sional arrays up to the limits of Mark NE; Albuquerque, NM 87123 available memory; Virtual arrays up FORTH DIMENSIONS II/6 Page 174 LETTERS Dear FIG, Also publishing programming examples would be helpful. I, for I have been using the May '79 one, find examples the best method release of 6800 fig-FORTH since it of learning and attempting to reach was issued. A question that isn't the point where I start building apparent on the order form is, has a FORTH programs efficiently. further release been made either on the assembly source listing or I also recognize that one person installation manual? This may be a can't do it all, and that a success- saving for us by preventing a dupli- ful users group depends upon cation of our software. contributions from everyone. I am not sure how I can help at this N.H. Champion time, but I am willing to do my Prescott, A2 share.

Two small changes have been made J. Arthur Graham to the FIG model. In screen # 23, Orinda, CA U* has been corrected for a carry bug. Screens 93 and 94 have been Glad to hear it! See this converted from assembly to high month's edition for programming level. The assembly listings have examples and this month's editor's not changed in the last year. Here column regarding helping out. -- ed. are the revisionlpublication dates for each FIG publication: Dear FIG, Publication Release -Date I am interested in corresponding Installation Manual 1.0 11/80 with others interested in FORTH on larger machines. I can be reached Listing at the address below.

8080 1.1 9/79 Stewart Rubenstein 6800 1 .o 5/79 HARVARD UNIVERSITY CHEMICAL LABS 6809 1 .o 6/80 12 Oxford St., Box 100 6502 Cambridge, MA 02138 9900 1 .o 3/81 80861 88 1 .o 3/81 PDP- 11 1.3 1/80 Dear FIG, PACE 1 .o 5/79 ALPHA MICRO 1 9/80 Would it be possible to include some tutorial artt-cles on the inner Hope this clarifies your workings of FORTH in FORTH question. -- ed. DIMENSIONS?

Being new to this language, [I Dear FIG, find] the functions of the inter- preters and the compiler somewhat I would like to see programming mysterious. examples as part of every meeting agenda. Perhaps a theme could be established for each meeting.

he175 FORTH DIMENSIONS II/6 Le71LRS

Given the extensibility of FORTH, DEA- FIG, a better understanding of the guts of the language is an advantage. I I AM A FOR-- PRO------CUR- - - -__ hdven't found a publication that Em-----BY FOR-- INC. 1 IIAV- NOT completely describes these functions. WOR--- ON ANY FIG TYP- SYS---- AND I AM EXC---- BY THE VAR----- LEN--- R. Stockhausen NAM- IDE-• PLE--- SEN- ME THE FIG Milwaukee, WI FOR-- MOD-- SO THA- I MAY TRY IT OUT HER- AT FOR-- IiJC. See Dr. C.H. Ting's SYSTEMS GUIDE TO flg-FORTH, available from FRE- THO---- FIG -- you can use the order blank at the back of this issue. -- ed. Your request is answered. Next edition you will be able to communi- cate with four+ letter words! -- ed. Dear FIG,

Our membership is growing and I Dear FIG, have delivered fig-FORTH8 to several of the Black African countries. I am a long time FIG member and am seriously devoted to FORTH as a Rhodes University has adopted programming language and system. 6809 fig-FORTH for its curriculum Like many others, I have FORTH this year. UNISA will follow, God running now and after all the talk willing, next year in its micro- about how great it is, I find few processor course, and several other (hardly any) complete examples of universities are using various its use in solving real, practical versions of fig-FORTH for research problems. purposes. The point of all this is a I've written several articles, suggestion that FIG publish more both local and abroad on FORTH and articles and papers on practical I'll send you copies of these. applications -- programs which can Please give us some support and be easily put into everyday use by coverage. I'll write you at least any programmer. One can go to the once a month. magazine counter at any computer store and find many examples of Ed Murray practical programs in BASIC. FORTH FORTHWITH COMPUTERS/FIGSA should be even more appropriate for P.O. Box 29452 such applications. Sunnyside, Pretoria, 0132 South Africa I believe that the organization, and each of us as members, can Always happy to hear from our contribute to this end. I propose international contingent! Your FIG strongly solicit contributions meeting announcements are in our of articles dealing with practical announcement section. -- ed. programing projects developed in FORTH.

George 0. Young I11 Albuquerque, NM

You took the words right out of our editorial mouths. We hear you and are looking forward to receiving contributions. -- ed.

FORTE DIHENSIONS II/6 Page 176 I have the rest of the FIG model Dear FIG, working, although I've had moments with it ranging from tears to I have developed a generalized apoplexy. I'VC discovered 'joint? of data structure for vocabularies the no-no's the hard wc3:r', also known which removes many of the limita- as "How to reconfigure \c),i~ disk -- tions now found in both FIG and unexpectedly." or "rhcre aid the other FORTH models. CPIM go?".

Xy new strcctilre has most of the I haven't had so IXUC ti t uL1 si lice advantages of the present FIG model, I built this "Unirr2.d X~tions pius it allows multiple threads per computer '* . vocabulary with different numbers of t!ireads in each, if desired. With Regard-, this multiple thread concept vocabu- Glenn Fdrnswartti laries are physically linked with a Weed, CA single pointer and are both sealed and linked simultaneously. Editor's note -- The editor was included with the mgdei ,is an extra I have also developed a "vocabu- "goodie". A little foresight would lary stack" to allow context speci- have told us the b502 assembly fication in line with the FORTH '79 source would prove to be an irritant. standard. I intend to make my The high level equivalent is given findings available at the next FORML below. A full screen searc?i with a conference. code MATCH takes about l50 msec, while the high level form requires If anyone would like to contri- over a second. Try the high level bute suggestions or developments version and then recode for your along these lines (especially the processor. This addition to the vocabulary stack) for release in the model was made in September 1980 public domain plEase write me at the thanks to Peter Midnight who address below: provided an earlier definition.

EXIT (in line with the 79-standard) Keep smiling! -- ed.

George W. Shaw I1 SHAW LABS, LTD. P.O. Box 3471 Hayward, CA 94540

Dear FIG,

Help! A while back I got my copy of TigFORTH-8080 version. I'm bogged down at the "MATCH" primitive of the "EDITOR" f unction. I 'm working alone at it as home computers are rare up here and FORTH is a "Very Foreign Language". All I need to know is what in tarnation one uses to inter- pret screens 93 & 94 to 8080 (or 280) code?

Page 177 FORTH DIMENSIONS I1/6 ANNOUNCEMENTS will devote an entire issue to FORTH. Interested authors s11ouId PREVIEWS OF COYIKG ATTRACTIONS (IN contact Marlin Ouverson, Editor; FPRTH DI?ENS!CIKS) : PEOPLE'S COMPUTER COElPAh'Y; PO Box E; Menlc, Park, CX 91,025 IsSLle Editori2.l Content ____. . . - - - .__ -__ -

?lay/Jun Applic I ions, utilities & CALL FOR PAPERS 11 s ea b 1 e programs FI1.. STAhl'AXDS 7 LA:'. It e FOZ?H -1~1,Aag C,irnes 14 game type appli- Stdnd.irds 7,~ii-3 aniio'li'tes tllr Sprinv cations Conference hosted by the University of Rochester on May 13th through May sep: or t L'niversity of Rochester & 15th, 1981. Larry Forsley is the i't restit conferences session organizer. This conference will have three coinponents: Formal Nnv/lki Graphics ri music papers, Sub-team working groups, and Poster sessio:is. If you would like to be a contri- buting author to any of the above Formal papers must be received by please write to: Editor; FORTH May 1st. Later material and informal DIMENSIONS; P.O. Box 1105; San presentations will be assigned to Carlos, CA 94070. You will be sent the "Poster session"; at which the a writer's kit that will make your authors will conduct clustered work- job easier. Please note deadlines shops, with attendees moving among for each issue are several months in the presentations. The Sub-teams advance of publication dates so will prepare short reports after allow plenty of time to produce your topic oriented working sessions. article. Working sessions are scheduled from the morning of May 13th through FIG GOES TO COMPUTER FAIRE: FIG lunch on May 15th. A reception will will have booth number 1137C at the be held on the evening of May 12th West Coast Computer Faire being held for early arrivals. Accomodations April 3 to 5 at Brooks Hall in San are $12.00 single occupancy and Francisco. $9.00 each, double occupancy. A combination of campus and off-campus meals are planned. FREE BUG FIXES: The 8080 Renovation Project wants bug reports so they Papers are specifically requested on: can get to work on fixing them. If you have found an 8080 Bug send it 1. Implemtation aspects of FORTH-79 to 8080 Renovation Project; c/o FORTH Interest Group; P.O. BOX 1105; 2. Refinements of vocabulary San Carlos, CA 94070 structure, extensible control structures, definition of input and output streams. DR. DOBBS NEEDS YOUR HELP: The editor of Dr. Dobb's Journal of 3. File sytem extension Computer Calisthenics & Orthodontia is very interested in articles on 4. Floating point extensions FORTH. If he can get enough, he

FORTH DIMENSIONS II/6 Page 178 The contact for submittal of papers and room reservations is Larry Forsley; Laboratory for Laser Ener- ATTENTION 65’32 USERS: getics; University of Rochester, NY 14623. Send room requests without The following seem to me to be delay; a confirmation with exact cost errors in the 6502 Assembly Source will be returned with the conference Listing (May 1980). I think I can schedule and travel suggestions. correct these errors easily enough, but I worry if maybe they have generated more subtle errors that I MEE’CI KG,’EVENT ANKOUNCEMENT FORMAT have not found. I have no experience with FORTH at all, so I’m not sure In order to have uniformity and what should be happening, and I have insure complete information in all no one I know with any experience to meeting and special event announce- call upon. ments, FORTH DIMENSIONS requests I that yo11 use the following format: Page 0061 UPDATE !+issing SEMIS at end? (There is one in the 1. WhO is holding the event installation manuX) (crganization, club, etc.) 0064 Line 3075 Shouldn’t this be a 2. WHAT is being held (describe backward branch with F6 FF as activity, speakers’ names, etc.) displacement?

3. WHEN is it being held (days, 0067 Lines 3204 - 3205 Two STX times, etc.; please indicate if XSAVE’s. Is one superfluous or is it is a repetitive event -- it replacing something else that monthly meeting etc.) really should be there?

4. WHERE is it being held (be as 0069 Lines 3280 - 3284 Two SEMIS. complete as possible -- room Again, is something being destroyed number, etc.) by the extra one?

5. WHY is it being held (purpose, C.A. McCarthy

objectives, etc.) Department of Mathematlcs Y Vincent Hall 5. REMARKS & SPECIAL, NOTES (is UNIVERSITY OF MINNESOTA there a fee, are meals/ Minneapolis, MN 55455 refreshments being provided, dress, tools, special require- ments, pre-requisites, etc.)

7. PERSON TO CONTACT

8. PHONE h’UMBER/ADDRESS (include area codes, times to call & give work & home numbers in case we need clarification) RENEW TODAY!

Page 179 FORTE DIMENSIONS 11/6 SOCTETE D' i?IF, .. . ti .i'~xi~itJR I)L MEETINGS QUEBEC: Iias c~ FORTH group (French!) that meets e'Jery othc>r beck. Anyone :i"KTi: I?.T:I.REST GROCP C .K.: Chair- from the Quebec .+rt',i who would iikts

'Vd IO StBi.re t ii rv./Trea~urtr: Harry Dobson; contact Gilles Paillard; 1310 Dtas ?kt.w$iet: tar Editor: Gil Filbey; Pins Est; Ancienne-l.orette; Quebec, ('ommi t tt'c Mcrnbers: Bill Powell, Canada G2E 1C2 or call (418) 3il1 Stc~,ddart. Meetings are held at 871-1960 p.3. on the 1st Thursday in every :'. r'~: r,;;t i, .!t : FIGSA: South Africa has a very active The Folvtechnic of the Southbank FORTH Interest Croup mLeting monthly Roon $08 and currently is offering FORTH 8ol-ough Road mini-courses to ground users in the i-O!iD('X fundamentals. Interested persons in the Johannesburg and Pretoria locales '!ai iing Address: can get more information regarding meetings and courses by contacting tORTtf INTERZST GROUP U.K. Ed Murray; FORTHWITH COMPUTERS; c'c) 36, Worsley Road PO Box 27175; Sunnyside Pretoria FrirnleL, Camberley, 0132, South Africa Surrey, GUlh 5AU EXGLAND SOUTHERN CALIFORNIA fig: Attendees numbered approximately thirty-five PORTI.AND FORTH USERS GROUP: Held and most had up and running FORTH its first meeting in January. Demos systems. Three books were reported: were given on an Apple 11. Also Threaded Interpretive Language by shown were a Hires graphic package Loeliger, which steps the reader writ ten in FORTH; A "de-FORTHer" through Z-80 source code of fig-FORTH program that takes FORTH words down for the TRS-80; MINT, Machine- to their component parts; and a 64 Independent Organic Software Tools, bit quad precision math package. by Godfrey, et al.; and FORTH SYSTEM FORTH concepts such as the word GUIDE by Ting which now has the DEPTH and .S (a non-destructive assembler in its final chapter. The stack print out) were also dis- formation of an Organge County fig cussed. Meetings are held monthly group was begun. at THE COMPUTER 6 THINGS STORE; 3460 S.W. 185th, Suite D; Aloha OR 97006 Martin Tracy of MicroMotion discussed Implementing Strings in FORTH, their 8th chapter in "FORTH-79 TULSA COMPUTER SOCIETY: A FORTH Tutorial and Reference Manual" (for Interest Group has been formed in the APPLE 11). This string package Tulsa, OK under the auspices of the compares, concatenates, converts and Tulsa Computer Society. The group arrays with words like GET$, INPUTS has 6502 figFORTH running on several and IN$ (which i.ndexes into the Apple 11's and 8080 figFORTH running String). on a Compucolor and a MITS Altair using CP/M and Micropolis Drives. For meeting information contact Art Gorski; c/o The Tulsa Computer Society; P.O. Box 1133; Tulsa, OK 74103 or call (918) 743-0113; (918) 743-4081

FORTH DIMENSIONS II/6 Page 180 AN OPEN RESPONSE Requirements derived from -the FOKT11-79 Standard :

We continually receive letters I asking if FORTH can be installed on a particular computer, particularly those without direct access mass storage or an ASCII terminal (i.e. PET, Vip, and Kim). Often, similar queries reflect a desire to use I cassette tape. This summary gives the general characteristics of a If you are missing .:r,y itr,~tr an ir- lation, an assembler is also needed. regular insLa1lation iud c~t!c>r portability prnblemr.. C!is c\lrst: j s FORTH is an interactive, compiled not caiised by FOGTII Init by t!ie language. This statement may be sho r t s i g h t r d 2 e s s o f ti ci r d w I’ t’ 1: c A-jd o c s . expanded to conclude that compilation FORTH is an environment tn which YOU requires mass storage for source can operate ‘3s a professional. We text; if must be random access to be know of no professional wh.3 kould A interactive. terminal is also demand to have his trrmirial line needed, as a hex keypad cannot be width reduced to 40 ctliiracterb, have deemed interactive. The character six ASCII characters removed rrom set must be complete for program his keyboard or returri his dlsk to portability, reflecting the common- the manufacturer as unnecessary. If ality of language. FORTH were compromised to iess than the above guidelines, we uould Requirements to execute: ultimately be operating from a hex keypad with paper tape. 1. A random access mass storage device with direct access to sector readlwrite i.e. disk or BENCHMARKING: diskette. Because there is almust universal 2- 16 Kilobytes of ram. disagreement on which are the most valid benchmark tests; and because 3. A keyboara input with at least in FORTH memory compactness may be the fu31 upper case ASCII char- traded off for execution speed at acter set. the implementor’s option, it is the policy of FORTH D1MENSIi)fZS i3 nini- 4. A display of at least 64 charac- mize the use of benchmark tests that ters by 16 lines. measure speed alone. Such single d imens iona 1 tests more precise 1y Requirements to install: measure the speed of d given CPU than the implementation df FORTH 1. An assembler that can accept itself and encouraging such simplis- about 80K of source producing tic testing will probably mean the about 5.5K of object, either compactness of FORTH will inevitably memory or disk. suffer. For tbese rezisons FORTH DIMENSIONS is normally oniy inter- ested in benchmark tests fhat measure both productivity (useful work) and speed as a better indicator of a given implementations value.

Page 181 FORTH DIMENSIONS II/6 Tn ’>!!-w ng vendors have venlm of 0s cam Coneurner Computem Ernperical Rer. Crp. FORTH available or are conaultmtr. (FIG 8907 LaMese Blvd. PO Box 1176 rnarcs rrr I 15n~ot00 any producta.) LaMesa, CA 92041 Milton, WA 98354 (714) 698-8088 (206) 651-4855

Software Federation filnwU8,~rd- ALWMlcRo M Lhiversity Dr. Oatrlcon Rsfr33 ??RI Wanagernent Services Arlington Heights, IL boo00 7911 NE 33rd Or. 724 .I*astradero Rd. 1109 (J12) 259-1355 Portland, OR 97211 >-‘o a!m, C 4 94306 003) 284-8277 J;‘’ E’8-2?18 Technic~lRoduCtr CO. P. 0. Box 12983 Forward Technology Sirrra ‘omputcr Co. Gainaville, FL 32604 2595 Martin Avenue b17 4vk NE (904) 372-8439 hnta Clara, CA 95050 4i:~uquerque, NM 87123 (408)295-8993 Tom Zlrnmer ME 292 Fslcato Dr. Rockwell Internatlone1 :LIj ‘Cap‘n Software) Milpitar, CA 95035 Mlcroelectronlca Devlnr 261 Arlington Avenw P.O. Box 3669 Rcrkclsv. CA 94704 6mo&6Kl9 Anaheim, CA 92803 525-9452 Talbot Microryatem (714) 632-2862 5030 Kenringtm Way Lcorqr: Lyons Rlverride, CA 92507 Zendex Corp. .‘PO uenderson St. (714) 781-0464 6398 hqherty Rd. Jrrsri City, NJ 07302 Dublln. CA 94566 20:) 651-2905 TRm Miller Microcomputer Sorvlcxm VWdy of FORM W Mi croMot ion I 61 Lake Shore Rd. Interactive Computer Syrt.mr, Inc. 12977 Wilrfrire Blvd. I506 Natlck, MA 01760 6403 Di Marco Rd. Los Angelen, CA 913025 (617) 653-6136 Tampa, FL Y3614 ‘ZlJ! 821-4340 The bftwue Fum Mountain Wow R.r CROSS COM-s P. 0. Box 2304 P. 0. Box 46s6 Nnu t ilus Syatsma ROrtOn, VA 22090 Mountaln View, CA 9oooO P.0. Box 1098 (415) 961-4103 Sante Cruz, CA 95061 Slrlur Syrtemr (408) 475-7461 7528 Oak Rldps Wy. Sqmnoft Anoc1at.r Knoxvllle, TN 37921 P.O. BOX 1628 plyFORTH (61s) 693-6585 Champaign, IL 61820 FORTH, Inc. (217) 359-2112 2309 Pacific Coart Wy. 6m Herrnma Beach, CA 90254 Glc C. Rehnke Crmltmh (213) 372-8493 WO 5 Ranch Wow Clrclo #61 Cmatlve Solutlar, Inc. Anaheim Hlllr, CA 92087 4801 Randolph Rd. LYNX Rockvllla, MD 20852 3301 Ocean Park 1301 mlmwnlQEPrn Santa Monica, CA 90405 Lmboratay Mlcrayrtbm Dove Boultm (213) 450-2466 4147 Beethoven St. 581 Ookridge Dr. Loa Angolea, CA 90066 Redwood Clty, CA 94062 M & B Deeign (213) 390-9292 (415) 368-3217 820 Sweethay Drh Sunnyvale, CA 94086 Tlmln Englneerlnq Ca Elmer W. Flttery 9575 Cene~~AVO. I€-2 110 Mc Cmgm Avenue Mlcropollr Son Dlsgo, CA 92121 Mt. Arlington, NJ 078% Shaw Laba. Ltd. (714) 455-9008 (21s) 66s-is80 P. 0. Box 5471 Hayward, CA 94540 APpUdm Rdupr Co FORTH (415) 276-6050 InnoSyr 504 Lakemeed Woy 2150 Shottuck Avmw Redwood Clty, CA 94062 mstr Berkeley, CA 94700 (415) S66-6324 The Software Work., Inc. (415) 843-8114 P. 0. Box 4386 inner AIXOU Mountain Vlcw, CA 96040 Declrlon Rsrourcea Cap. Sl7K Marine Wow (408) 756-4738 28203 Rlckjefem Ct. Belmnnt, CA 94002 Rancho Palo Verd~,CA 90274 (415) 591-8291 PDP-11 (213) 377-3533 L-boratory bftwue Syrtsm, Inc. Hwrry- 3634 Mandevllle Cmym Rd KW3 Carp. 1259 Cnrnoll Lor Angolea, CA 90049 PO Box 27246 8.?ksloy, CA 947M (213) 472-6995 TUCOOII, AZ 85726 (415) 525-8582

Jahn!Lhnea P. 0. Box SMI Serkoley, CA 94701 FORTH DIMENSIONS 11/6 Page 182 NEW PRODUCT ANNOUNCEMENT FORMAT In the interests of comparison 16. Approximate number of product uniformity and completeness of data shipments tc date (product must in new product announcements FORTH have active installations as of DIMENSIONS requests that all future writing -- no unreleased new product announcements use the product 6) following format: 17. Product Price

1. Vendor name (company) 18. What price includes (shipping, tax, etc.) 2. Vendor street address (P.O. Boxes alone are not acceptable 19. Vendor warranties, post sale for mail order) support, etc.

3. Vendor mailing address (if 20. Order turn around time different from street address)

4. Vendor area code and telephone HELP WANTED number Openings for a project manager 5. Person to contact and senior programmer. Both positions offer the opportunity to work on a 6. Product name wide variety of projects, including systems programming and real-time 7. Brief description of product scientific and industrial applica- uselfeatures tions. Salary and benefits are excellent. A starting bonus is 8. List of extras included (editor, available for anyone with a substan- assembler, data base, games, tial FORTH background. Cont ac t etc.) FORTH, Inc.; 2309 Pacific Coast Highway; Hermosa Beach, CA 90254; 9. List of machines product runs on (213) 372-8493 10. Memory requirements Programmer analyst to work and 11. Number of pages in manual live in the Miami area who is trained and experienced in the CYBOS lan- 12. Tell what manual covers guage. Contact Keller Industries, Inc. , 18000 State Road 9, Miami, FL 13. Indicate whether or not manual 33162; (305) 651-7100, ext. 202. is available for separate purchase FORTH programer for computer 14. If manual is available indicate graphics. Contact Cornerstone Asso- separate purchase price and ciates, 479 Winter St., Waltham, MA whether or not manual price 1s 02154; (617) 890-3773. credited towards later purchase

15. Form product is shipped in (must be diskette or ROH - no IUH only or tape systems) RENEW TODAY! FORTH, INC. NEWS PAGE FORTH - 79 : ThIs Is the first in a series of columns highlighting various Al Krever is working on a new activities at FORTH, Inc. release of polyFORTH scheduled for March. This new release will RECENT APPLICATIONS: feature many improvements in all systems, plus greater compatability In December Chuck Moore com- with the FORTH - 79 Standard. pleted work on a 24-channel video mixer for Homer & Associates, a The FORTH - 79 edition of USING producer of films for promotioal and FORTH has been sent to the printers entertainment purposes in Hollywood. and will be available after mid- This 2-80 based system controls 16 February. slide projectors, four movie projec- tors and audio tape. It has mas- POLYFORTH COURSES: tering and sequencing capabilities which Peter Conn, Homer's president, FORTH, Inc. offers two courses-- says are unique In the industry. an introductory course for program- mers unfamiliar with polyFORTH and In early January American Air- an advanced course designed for those lines performed the final acceptance with considerable FORTH experience of the LAX outbound baggage system who desire greater familiarity with developed by Dean Sanderson and Mike system level functions, target com- LaManna. The system runs on two piling and other advanced techniques. PDP-11 computers (one functions as a backup), and controls several con- FORTH, Inc.'s course schedule veyor belts, bag encoder stations, for the next few months is: electric eye sensors, and printers. It is more accurate and has 25% Month Introductory Advanced better performance than the all- assembly language system it replaced. April 6 - 10 13 - 17 May 11 - 15 (tentative) NEW PRODUCTS: Contact Carol Ritscher at FORTH, EXORset polyFORTH pF6809/30, Inc. (213) 372-8493 for more infor- developed by Mike LaManna, is our mation. newest product and runs on the Motorola EXORset 30 -- a micro- SEMINARS d WORKSHOPS: computer featuring a 6809 processor, graphics CRT and two mini-floppies A series of completely new in a single compact box. EXORset half-day seminars and one-day work- polyFORTH sells for $4750 and shops has been scheduled in several incudes a secial screen editor; a cities. Both present an overview of high-speed graphics option with the features and benefits of poly- software vector and character FORTH for professional users. The generation; labeled graphs with EXORset and tls new graphics package several plotting modes; a "strip- will be featured. chart" function with snap-shot capabilities, and several demon- city Seminar Workshop stration routines. EXORset polyFORTH sells for $4750.00. The option Washington, DC 3/19 3/20 package sells for $500.00. Both Houston 4/21 4/22 will be featured at FORTH, Inc.'s Boston 4/23 4/24 spring seminar series. Contact Carol Ritscher at FORTH, Inc. (213) 372-8493 for mare information.

FORTR DIMENSIONS 11/6 Page 184 ! Seattle Chuck Pliske or Dwight Vandenburg at now to form a FIG Chapter: (206) 542-8370.

1. You decide on a time and place Potomac Paul van der Eijk at (703) for the first meeting in your 354-7443 or Joel Shprentz area. (Allow about 8 weeks for at (703) 437-9218. steps 2 and 3.) Tulsa Art Gorski at (918) 743-Oil3 2. Send to FIG in San Carlos, CA a meeting announcement on one Texas Jeff Lewis at (713) 729-3320 side of 8-1/2 x 11 paper (one or John Earls at (214) copy Is enough). Also send 661-2928 or Dwayne Gustaus list of ZIP numbers that you at (817) 307-6976. John want mailed to (use first three Hastings (512) 835-1918 digits if it works for you). Phoenix Peter Bates at 3. FIG will print, address and (602) 996-8398 mail to members with the ZIP'S you want from San Carlos, CA. Oregon Ed Krammerer at ( 503) 644-2688. 4. When you've had your first meeting with 5 or more atten- New York Tom Jung at (212) 746-4062. dees then FIG will provide you with names in your area. You Detroit Dean Vieau at have to tell us when you have (313) 493-5105. 5 or more. England FORTH Interest Group, c/o Northern California 38, Worsley Road, Frimley, 4th Saturday FIG Monthly Meeting, Camberley, Surrey, GU16 5AU, 1:00 p.m., at Southland England. Shopping Ctr., Hayward, CA. FORML Workshop at Japan Mr. Okada, President, ASR 1O:OO a.m. Corp. Int'l, 3-15-8, Nishi- Shimbashi Manato-ku, Tokyo, Southern California Japan. 4th Saturday FIG Meeting, 11:OO a.m. Allstate Savings, 8800 Quebec, Canada So. Sepulveda, L.A. Gilles Paillard at Call Phillip Wasson, (418) 871-1960. (213) 649-1428. Publishers Note: Maesachuset ts 3rd Wednesday MMSFORTH Users Group, Please send notes (and reports) 7:OO p.m., Cochituate, about your meetings. MA. Call Dick Miller at .(617) 653-6136 for site.

San Diego Thur sdaye FIG Meeting, 12:00 noon. Call Guy Kelly at (714) 268-3100 x 4784 for site. RENEW TODAY!

hgc! 185 FORTH DIMENSIONS 1116