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

11I, 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 HISTORICAL PERSPECTIVE have members all over the world including the People’s 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 ), message routing tables, Abstract 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 - , ; NOT styled Editor and announced sale of 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