Barclay College Forth Language and Operating System Project
Using this pdf bookStarting-FORTH.pdf
Download Starting-FORTH.pdf
as a reference, solve the following problems:
1. Create a Word Called MIX that will take the following list of numbers (placed on to
the stack) [50 pts]
2345
and leave these on the stack after the execution of MAX
235554
The usage should be
2 3 4 5 MIX
The word must also print the contents of the stack before and after execution.
2. Create a word called WEDGE that will print out a wedge of asterixis in the shape of a
triangle, like so [100 pts]
*
**
***
****
*****
The usage would be
n WEDGE
where n is the number of lines in the wedge. Hint: you might want to break up this
word into sub words that print a single asterix, then one that prints out a number of
them on a line.
3. Create a Word called MIX2 that takes the following numbers [50 pts]
123456
and leaves the following on the stack
12653465
The word should print the stack before and after execution.
4. Create a word called MIX4 that takes the following numbers [50 pts]
123456
and leaves the following on the stack
3412256
The word should print the stack before and after execution.
Starting FORTH
Starting FORTH
An Introductionto the FORTH
Language
andOperating
System
for BeginnersandProfessionals
LeoBrodie,
FORTH. Inc.
+
With a foreword by
Charles H. Moore
Prentice-Hall, Inc., Englewood Cliffs, NJ 07632
library of CongressCatalogingin PublicationData
BRODIE, LEO.
Starting FORTH.
I. FORTH (Computer program language) I. Title.
QA76.73.F24B76
001.64’24
81-11837
ISBN 0-IJ-842930-8
AACR2
ISBN 0-13-842922-7 (pbk.)
Publisher’s credits:
Editorial / production supervision: Kathryn Gollin Marshak
Manufacturing buyer : Gordon Osbourne
Paper cover design: FORTH, Inc. and Alon Jaediker
Case cover design: Edsal Enterprises
The pages of this book were reproduced
from camera ready copy
designed and prepared by FORTH, Inc.
© 1981 by FORTH, Inc., Hermosa Beach, CA 90254
All rights reserved. No part of this book
may be reproduced in any form or by any means
without permission in writing from the publisher.
Printed in the United States of America
19 18 17 16 15 14 13 12
Prentice-Hall International, Inc., London
Prentice-Hall of Australia Pty. Limited, Sydney
Prentice-Hall of Canada, Ltd., Toronto
Prentice-Hall of India Private Limited , New Delhi
Prentice-Hall of Japan, Inc., Tokyo
Prentice-Hall of Southeast Asia Pte. Ltd., Singapore
Whitehall Books Limited, Wellington, New Zealand
ABOUT THE AUTHOR
Leo Brodie’s
inability
to express
even
the most complex
technical
concepts
without adding a twist of humor comes from an
early love of comedy.
He specialized
in playwriting
at UCLA and
has had several
comedies
produced
there
and in local
theater.
He has also written
freelance
magazine articles
and has worked as
a copywriter
for an ad agency.
When a company he was working
for installed
a computer,
he became inspired
to try designing
a
microprocessor-based
toy.
Although he never got the toy running,
he learned
a lot about computers
and programming.
He now works
at FORTH, Inc. as a technical
and marketing
writer,
where he can
play on the computers as the muse determines
without having to be
a fanatical
computer jockey,
and is allowed
to write books such
as this.
Leo’s other interests
include
dancing to 50’s music.
singing,
V
driving
classic
Volvos,
and
FOREWORD
The FORTH community can celebrate
a significant
event with the
publication
of Starting
FORTH. A greater
effort,
talent,
and
commitment
have gone into this
book than into any previous
introductory
~anual.
I, particularly,
am pleased
at this evidence
of the growing popularity
of FORTH, the language.
I developed
FORTH over a period
of some years as an interface
between
me and the computers
I programmed.
The traditional
languages
were not providing
the power, ease, or flexibility
that
I wanted.
I disregarded
much conventional
wisdom in order to
include
exactly
the capabilities
needed
by a productive
programmer . The most important
of these
is the ability
to add
whatever capabilities
later become necessary.
The first time I combined the ideas I had been developing
into a
single entity,
I was working on an IBM 1130, a “third-generation”
computer.
The result
seemed so powerful
that I considered
it a
“fourth -generation
computer
language.”
I would have called
it
FOURTH, except
that
the 1130 permitted
only five-character
identifiers
. So FOURTH became
FORTH, a nicer
play on words
anyway.
One principle
that guided the evolution
of FORTH, and continues
to guide its application,
is bluntly:
Keep It Simple.
A simple
solution
has elegance.
It is the result
of exacting
effort
to
understand
the real problem and is recognized
by its compelling
sense of rightness.”
I stress
this point
because
it contradicts
the conventional
view that power i ncreases
with complexity.
Simplicity
provides
confidence,
reliability,
compactness,
and
speed.
·
Starting
FORTH was written
and illustrated
by Leo Brodie,
a
remarkably
capable
person
whose insight
and imagination
will
become
apparent.
This book is an orig i nal and detailed
It deftly
guides the novice over the
prescription
for learning.
thresholds
of understanding
that all FORTH programmers
must
c r oss.
Although I am the only p e rson who has never had to learn FORTH,
I oo know that its study is a formidabl e one.
As with a human
language,
the usage
of many words must be memorized.
For
beginners,
Leo’s droll
comments
and supe r bly cast characters
appear
to make this study easy and enjoyable.
For those like
myself
who al r eady know FORTH, a quick reading
provides
a
vi i
delightful
trip and fresh views of familiar
terrain.
But I hope
this book is not so easy and enjoyable
that it seems trivial.
Be
warned that there is heavy content
here and that you can learn
much about computers and compilers
as well as about programming.
FORTH provides
a natural
means of communication
between man and
the smart machines
he is surrounding
himself with.
This requires
that
it share
characteristics
of human languages,
including
compactness,
versatility,
and extensibility.
:t: cannot imagine a
better
language
for writing
programs,
expressing
algorithms,
or
understanding
computers.
As you read this book, I hope that you
may come to agree.
Charles
Inventor
H. Moore
of FORTH
viii
ABOUT THIS BOOK
Welcome to Starting
FORTH, your introduction
powerful computer language
called
FORTH.
to an exciting
and
If you’re
a beginner
who wants to learn
more about computers,
FORTH is a great
way to learn.
FORTH is more fun to write
programs
with than
any language
that
I know of.
(See the
“Introduction
for Beginners.”)
If you are a seasoned
professional
who wants to learn FORTH, this
book is just what you need.
FORTH is a very different
approach
to computers,
so different
that everyone,
from newcomers to old
hands, learns
FORTH best from the ground up. If you’re adept at
other computer languages,
put them out of your mind, and remember
only what you know about computers.
(See the “Introduction
for
Professionals,
‘1)
Since many people
with different
backgrounds
are interested
in
FORTH, I’ve arranged
this book so that you’ll
only have to read
what you need to know, with footnotes
addressed
to different
kinds of readers.
The first half of Chap. 7 provides
a background
in computer arithmetic
for beginners
only.
This book
includes
high-level,
extremely
operators
“FORTH-79
explains
how to write simple applications
in FORTH. It
all standard
FORTH words that
you need to write
a
single-task
application.
This word set is an
powerful
one, including
everything
from simple math
to compiler-controlling
words.
(See Appendix
3,
Standard.”)
Excluded from this book are all commands that are r e lated to the
assembler,
multiprogrammer,
printing
and disking
utilities,
and
target
compiler.
These commands are available
on some versions
of FORTH such as polyFORTH.
(See Appendix 2, “Further
Features
of polyFORTH. “)
I’ve chosen
examples
that will actually
work at a FORTH system
with a terminal
and disk.
Don’t infer
from this that FORTH is
limited
to batch or string – handling
tasks, since there
is really
no limit to FORTH’s use fulne s s.
Here are some features
All commands
are listed
of this
twice:
book that
first,
ix
will
in the
make it easy
section
to use:
in which
the
word is introduced,
chapter.
Appendix
and second, in the summary at the end of that
4 provides
an index to the tables.
Each chapter
also has a review of terms
problems.
Appendix 1 lists the answers.
and
a set
of exercise
Several
“Handy Hints” have been included
to reveal
procedural
tips or optional
routines
that are useful for learners
but that
don’t merit an explanation
as to how or why they work.
A personal
note:
FORTH is a very unusual language.
It violates
many cardinal
rules of programming.
My first
reaction
to FORTH
was extremely
skeptical,
but as I tried
to develop
complicated
applications
I began to see its beauty and power.
You owe it to
yourslf
to keep an open mind while reading
about some of its
peculiarities.
I’ll
warn you now:
few programmers
who learn
FORTH ever go back to other languages.
Good luck,
and enjoy
learning!
Leo Brodie
FORTH, Inc.
X
ACKNOWLEDGEMENTS
I’d like to thank
book possible:
the
following
people
who helped
to make this
For consultation
on FORTH technique
and style:
Dean Sanderson,
Mich ae l LaManna, Jam e s Dewey, Edward K. Conklin,
and Elizabeth
D. Rather, all of FORTH, Inc.; for providing
insights
into the art
of teaching
FORTH and for writing
several
of the problems in this
book:
Kim Harris of the FORTH Interest
Group; for proofreading,
editorial
suggestions,
and enormous amounts of work formatting
the pages:
Carolyn A. Rosenberg;
for help with typing
and other
necessities:
Sue Linstrot,
Carolyn
Lubisich,
Kevin Weaver, Kris
Cramer, and Stephanie
Brown Brod i e; for help with the graphics:
Carolyn
Lubisich,
Jim Roberts,
Janine
Ritscher,
Dana Rather,
Winnie Shows, Natasha Elbert,
Barbara Roberts, and John Dotson of
Sunrise
Printery
(Redondo Beach, CA); for technical
assistance,
Bill Patterson
and Gary Friedlander;
for constructive
criticism,
much patience
and love:
Stephanie
Brown Brodie;
and for
inventing
FORTH, Charles H. Moore.
xi
TABLE OF CONTENTS
ABOUT THE AUTHOR
FOREWORDby Charles
V
vii
H. Moore
ABOUT THIS BOOK
ix
ACKNOWLEDGEMENTS
xi
INTRODUCTIONS
Introduction
Introduction
1
1
1
for Beginners
. for Professionals
FUNDAMENTALFORTH
A Living Language
All This and ••• Interactive!
The Dictionary
Say What?
The Stack:
FORTH’s Worksite
Postfix
Power
Keep Track of Your Stack
Review of Terms
Problems
3
7
7
9
for Arithmetic
14
18
19
22
24
27
29
2
HOW TO GET RESULTS
FORTH Arithmetic – -Calculator
Style
For Adventuresome
Newcomers Sitting
at a Terminal
Postfix
Practice
Problems (Quizzie 2-a)
FORTH Arithmetic
– Definition
Style
Definition-style
Practice
Problems (Quizzie 2-b)
The Division
Operators
Stack Maneuvers
Stack Manipulation
and Math Definitions
(Qui zz i e 2-c)
Playing
Doubles
Review of Terms
Problems
31
31
33
37
38
41
42
44
51
52
54
55
3
THE EDITOR (AND STAFF)
Another Look at the Dictionary
How FORTH Uses the Disk
Dear EDITOR
Character
Editing Commands
The Find Buffer and the Insert Buffer
Line Editing Commands
Miscellaneous
EDITOR Commands
Getting !LOAD!ed
Review of Terms
Problems
57
57
59
63
66
69
73
75
79
86
87
xiii
4
DECISIONS,
DECISIONS,
89
89
92
93
95
97
101
104
105
•••
The Conditional
Phrase
The Alternative
Phrase
Nested ~ ••• THEN Statements
A Closer Look at IF
A Little Logic
Two Words with Built-in
[!!:ls
Review of Terms
Problems
5
THE PHILOSOPHY OF FIXED POINT
Quickie Operators
Miscellaneous
Math Operators
The Return Stack
An Introduction
to Floating-Point
Why FORTH Programmers Advocate
Star-slash
the Scalar
Some Perspective
on Scaling
Using Rational
Approximations
Review of Terms
Problems
Arithmetic
Fixed-Point
107
107
108
109
113
114
116
119
121
124
125
6
THROWIT FOR A LOOP
Definite
Loops — ~ ••. ILOOPI
Getting [g}fy
Nested Loops
+LOOP
DOing It — FORTH Style
Indefinite
Loops
The Indefinitely
Definite
Loop
Review of Terms
Problems
127
127
131
132
133
135
138
140
144
145
7
A NUMBEROF KINDS OF NUMBERS
I. FOR BEGINNERS
149
150
Signed
vs.
Unsigned
Numbers
Arithmetic
Shift
An Introduction
to Double-length
Numbers
Other Number Bases
The ASCII Character
Set
Bit Logic
II. FOR EVERYBODY
Signed and Unsigned Numbers
Number Bases
Double – length Numbers
Number Formatting
— Double-length
Unsigned
Number Formatting
— Signed and Single-length
Double-length
Operators
Mixed-length
Operators
Numbers in Definitions
Review of Terms
Problems
xiv
150
153
154
155
156
158
160
160
162
164
166
170
173
174
176
180
181
8 VARIABLES,CONSTANTS,ANDARRAYS
Variables
A Closer Look at Variables
Using a Variable as a Counter
Constants
Double-length Variables and Constants
Arrays
Another Example — Using an Array for Counting
Factoring Definitions
Another Example — “Looping” through an Array
Byte Arrays
Initializing
an Array
Review of Terms
Problems
190
193
195
199
202
204
206
207
211
212
9 UNDERTHE HOOD
Inside !INTERPRET!
Vectored Execution
The Structure of a Dictionary Entry
The Basic Structure of a Colon Definition
Nested Levels of Execution One Step Beyond
Abandoning the Nest
FORTHGeography
The Geography of a Multi – tasked FORTHSystem
User Variables
Vocabularies
Review of Terms
Problems
215
215
217
220
224
225
228
229
231
238
240
242
248
251
10 I/0 ANDYOU
Block Buffer Basics
Output Operators
Outputting Strings from Disk
Internal String Operators
Single – character Input
String Input Commands, from the Bottom up
Number Input Conversions
A Closer Look at IWORDI
String Comparisons
Review of Terms
Problems
xv
183
183
186
188
253
253
258
261
266
268
270
277
280
281
286
287
11 EXTENDINGTHE COMPILER:
DEFINING WORDSANDCOMPILINGWORDS
Just a Question of Time
How to Define a Defining Word
Defining Words You Can Define Yourself
How to Control the Colon Compiler
More Compiler-controlling
Words
An Introduction
to FORTH Flowcharts
Curtain Calls
Review of Terms
Problems
289
289
290
293
299
303
307
309
314
315
12 THREE EXAMPLES
IWORDIGame
File Away!
No Weighting
Review of Terms
317
318
328
341
348
APPENDICES
1.
Answers to Problems
2.
Further
3.
FORTH-79 Standard
4.
Summary of FORTHWords
Features
of polyFORTH
TABLE OF HANDYHINTS
Non-Destructive
Stack Print
When a Block Won’t IL?ADI
A Better Non-Destructive
Stack Print
How to Clear the Stack
!PAGE)and !QUIT)
A Definition
for BINARY– or Any-ARY
How to ILOCATEIa Source Definition
A Random Number Generator
Two Convenient Additions to the Editor
Entering Long Definitions
from Your Terminal
A
xvi
50
82
83
137
142
163
245
265
269
306
Starting FORTH
INTRODUCTIONS
Introduction
for Beginners:
What Is a Computer Language?
At first,
when beg inners
hear
the term “computer
language,”
they wonder,
“What kind of
language
could
a computer
possibly
speak?
It must be
awfully
hard for people
to
understand.
It probably
looks
like:
976# !@NX714&+
if it
all.”
looks
like
anything
at
Actually,
a computer language
should
not be difficult
to
understand.
Its purpose
is
simply to serve as a convenient
compromise
for communication
between person and computer.
Consider
the marionette.
You
can make a marionette
“walk”
simply by working the wooden
control,
without even touching
the strings.
You could say that
rocking
the control
means
“wal king” in the language of the
marionette.
The puppeteer
guides the marionette
in a way
that
the
marionette
can
understand
and
that
the
puppeteer can easily master.
Computers are machines just like
the marionette.
They must be
told exactly
what to do, in
specific
language.
And so we
need a language which possesses
two seeming l y opposite traits:
1
2
Starting
FORTH
On the one hand, it must be precise
in its meaning
to the
computer, conveying
all the information
that the computer needs
to know to perform the operation.
On the other hand, it must be
simple and easy-to-use
by the programmer.
Many languages have been developed since the birth of computers:
FORTRAN is the elder
statesman
of the field;
COBOL is the
standard
language
for business
data processing;
BASIC was
designed
as a beginner’s
language
along
the road toward
languages
like FORTRAN and COBOL. This book is about a very
different
kind of language:
FORTH. FORTH’s popularity
has been
gaining steadily
over the past several years, and its popularity
is shared among programmers in all fields.
All the languages
mentioned above, including
FORTH, are called
“high-level”
languages.
It’s
important
for beginners
to
recognize
the difference
between a high-level
language and the
computer it runs on. A high-level
language looks the same to a
programmer regardless
of which make or model of computer it’s
running
on.
But each make or model has its own internal
language,
or “machine language.”
To explain
what a machine
language is, let’s return to the marionette.
Imagine that there is no wooden control
and that the puppeteer
has to deal directly
with the strings.
Each string corresponds
to
exactly
one part of the marionette’s
body.
The harmonious
combinations
of movements of the individual
strings
could be
called the marionette’s
“machine language.”
Now tie the strings
to a control.
The
control
is like a high-level
language.
With a simple
turn of the wrist,
the
puppeteer
can move many strings
simultaneously.
So it is with a high-level
computer
language,
where the simple and familiar
symbol”+”
causes
many internal
functions
to be performed in the process
of addition .
Here’s
a very clever
thing
about
a
computer:
it can be programmed
to
translate
high-level
symbols (such as
“+”) into the computer’s
own machine
language.
Then it can proceed to carry
out the
machine
instructions.
A
high-level
language
is a computer
program
that
translates
humanly
understandable
words and symbols into
the machine language
of the particular
make and model of computer.
a high-level
symbol used in
your program
•
•
high-level
language
machine
instruction
machine
instruction
machine
instruction
machine
instruction
machine
language
Starting
FORTH
3
What’s the difference
between
FORTH and other high-level
languages?
To put it very briefly:
it has to do with the
compromise between man and computer.
A language
should be
designed for the convenience
of its human users, but at the same
time for compatibility
with the operation of the computer.
FORTH is unique among languages
because its
problem is unique. This book will explain how.
Introduction
for Professionals:
solution
to this
FORTH in the Real World
FORTH has enjoyed a rising tide of popularity
in recent years,
perhaps most visibly
among enthusiasts
and hobbyists.
But this
development
is only a new wrinkle in the history
of FORTH.
FORTH has been in use for over ten years in critical
scientific
and industrial
applications.
In fact,
if you use a mini- or
microcomputer
professionally,
chances are that FORTH can run
your application–more
efficiently
than the language
you’re
presently using.
Now you’ll probably ask rhetorically,
“If FORTH is so efficient,
how come I’m not using it?”
The answer is that you, like most
people, don’t know what FORTHis.
To really get an understanding
of FORTH, you should read this
book and, if possible,
find a FORTH system and try it for
yourself.
For those of you who are still
at the bookstore
browsing, however, this section will answer two questions:
“What
is FORTH?” and “What is it good for?”
FORTHis many things:
–a
–an
–an
–a
–a
high-level
language
assembly language
operating system
set of development tools
software design philosophy
As a language,
FORTH begins with a powerful set of standard
commands, then provides the mechanism by which you can define
your own commands.
The structured
process
of building
definitions
upon previous definitions
is FORTH’s equivalent
of
high-level
coding.
Alternatively,
words may be defined directly
in assembler mnemonics, using FORTH’s assembler.
All commands
are interpreted
by the same interpreter
and compiled by the same
compiler, giving the language tremendous flexibility.
The highest
level
of your code will resemble
an English-language
4
Starting
description
of your application.
“meta-application
language”–a
create problem-oriented
languages.
FORTH has
language
that
FORTH
been called
a
you can use to
an operating
system, FORTH does everything
that traditional
operating
systems do, including
interpretation,
compilation,
assembling, virtual memory handling,
I/O, text editing,
etc.
As
But because the FORTH operating
system is much simpler than its
traditional
counterparts
due to FORTH’s design, it runs much more
quickly, much more conveniently,
and in far less memory.
What is FORTH good for?
a processor’s
efficiency.
FORTH offers a simple means to maximize
For example:
FORTH is fast.
High-level
FORTH executes
faster
than other
20 and 75% slower
than
high-level
languages
and between
equivalent
assembly-language
programs, while time-critical
code
may be written
in assembler
to run at full processor
speed.
Without
a traditional
operating
system,
FORTH eliminates
redundancy and needless run-time error checking.
FORTH compiled code is compact.
FORTH applications
require less
memory than their
equivalent
assembly-language
programs!
Written in FORTH, the entire
operating
system and its standard
word set reside
in less than BK bytes.
Support
for a target
application
may require less than lK bytes.
FORTH is transportable.
every
mini-
and
It has been
microcomputer
known
to
implemented
the
on just
about
industry.
FORTH has been known to cut program development
time by a factor
of ten for equivalent
assembly-language
programming
and by a
factor
of two for equivalent
high-level
programming.
Productivity
increases
because
FORTH epitomizes
“structured
programming” and because it is interactive
and modular.
Here are a few samples
of FORTH in the real
world:
Process
Control–FORTH
is being used to steer
the robot
motion-picture
cameras to create the special
effects
used in
the film “Battle
Beyond the Stars.”
FORTH was chosen
because
of its speed and its flexibility
in providing
an
interface
by which the operator
can describe
the camera
motion.
Other process-control
applications
range from a
baggage handler
for a major U.S. airline
to a peach sorter
for a California
cannery.
Portable
Intelligent
Devices–The
variety
of applications
which run FORTH internally
include
a heart
monitor
for
outpatients,
an automotive
ignition
analyzer,
a hand-held
instrument to measure relative
moisture in different
types of
grain, and the Craig Language Translator.
Starting FORTH
5
Medical–On a single PDP-11 at a major hospital,
FORTH
simultaneously maintains a large patient database; manages
thirty-two
terminals
and an optical
reader;
performs
statistical
analysis
on the database
to correlate
physical
types, diseases,
treatments,
and results;
and analyzes blood
samples and monitors heartbeats
in real time.
Data Acquisition
and Analysis–A
single
PDP-11/34 running
under FORTH controls
an entire
observatory,
including
an
extraordinarily
accurate
telescope,
the dome, several CRTs,
a clock, a line printer,
and a floppy disk drive–and
still
has time for taking data on infrared
emissions from space,
analyzing the data, and displaying
the results on a graphics
monitor.
Applications
of this type often make use of Fast
Fourier and Walsh Transforms,
numerical
integration,
and
other math routines written in FORTH.
There’s
a catch,
we must admit.
It is that FORTH makes .YQ!!
responsible
for your computer’s efficiency.
To draw an analogy:
a manual transmission
is tougher to master than an automatic, yet
for many drivers it offers improved control over the vehicle.
Similarly,
FORTH is tougher to master than traditional
high-level
languages,
which essentially
resemble one another
(i.e., after
learning
one, it is not difficult
to learn
another).
Once
mastered,
however, FORTH gives you the capability
to minimize
CPU time and memory space, as well as an organizing
philosophy
by which you can dramatically
reduce project development time .
And remember, all of FORTH’s elements enjoy the same protocol,
including
operating
system, compiler,
interpreters,
text editor,
virtual
memory, assembler,
and multiprogrammer.
The learning
curve for FORTH is much shorter than that for all these separate
elements added together.
If any of this
FORTH.
sounds
exciting
to you, turn
the page
and start
1
FUNDAMENTAL FORTH
In this chapter
we’ll
acquaint
you with some of the unique
properties
of the FORTH language.
After a few introductory
pages
we’ll have you sitting
at a FORTH terminal.
If you don’t have a
FORTH terminal,
don’t worry.
We’11 show you the result of each
step along the way.
A Living
Language
Imagine that you’re an office
manager and you’ve just hired a
new, eager assistant.
On the first day, you teach the assistant
the proper
format for typing
correspondence.
(The assistant
already
knows how to type.)
By the end of the day, all you have
to say is “Please type this.”
On the second day, you explain
the filing
morning to explain
where everything
goes,
all you have to say is “Please file this.”
system.
It takes all
but by the afternoon
By the end of the week, you can communicate
in a kind of
shorthand,
where “Please send this letter”
mean-s “Type it, get me
to sign it, photocopy
it, file the copy, and mail the original.”
Both you and your assistant
are free to carry out your business
more pleasantly
and efficiently.
Good organization
and effective
1.
define
useful
2.
group related
each of these
FORTH lets you organize
to a computer
in just
“Please”).
tasks
communication
and give
require
that
you
each task a name, then
tasks together
into
a name, and so on.
larger
tasks
and give
your own procedures
and communicate them
this way (except
you don’t
have to say
As an example,
imagine
a microprocessor-controlled
washing
machine
programmed
in FORTH. The ultimate
command in your
example is named WASHER. Here is the definition
of WASHER, as
written in FORTH:
7
8
Starting
: WASHER
In FORTH,
The first
procedure.
comprise
semicolon
FORTH
WASH SPIN RINSE SPIN ;
the colon indicates
the beginning
of a new definition.
word after
the colon,
WASHER, is the name of the new
The remaining
words, WASH, SPIN, RINSE, and SPIN,
the “definition”
of the new procedure.
Finally,
the
indicates
the end of the definition.
0
0
0
SJ
Each of the
already
been
example, let’s
words compr1s1ng
the definition
defined
in our washing-machine
look at our definition
of RINSE:
: RINSE
of WASHER has
application.
For
FILL AGITATE DRAIN;
As you can see, the definition
of RINSE consists
of a group of
words:
FILL, AGITATE, and DRAIN. Once again,
each of these
words has been already
defined
elsewhere
in our washing-machine
application.
The definition
of FILL might be
: FILL
FAUCETS OPEN TILL-FULL
FAUCETS CLOSE ;
In this definition
we are referring
to things
(faucets)
as well as
to actions
(open
and close).
The word TILL-FULL
has been
defined
to create
a “delay
loop” which does nothing
but mark
time until the water-level
switch has been activated,
indicating
that the tub is full.
If we were to trace
these definitions
back, we would eventually
find that they are all defined
in terms of a group of very useful
commands that form the basis of all FORTH systems.
For example,
polyFORTH
includes
about
300 such commands.
Many of these
commands are themselves
“colon definitions”
just like our example
words; others are defined
directly
in the machine language
of the
particular
computer . In FORTH, a defined
command is called
a
“word.” t
t For
Old Hands
This meaning
of “word”
is not to
value, which in the FORTH community
be associated
with a 16-bit
is referred
to as a “cell.”
1 FUNDAMENTAL
FORTH
9
The ability
to define a word in terms of other words is called
“extensibility.”
Extensibility
leads to a style of programming
that is extremely
simple,
naturally
well-organized,
and as
powerful as you want it to be.
Whether your application
runs an assembly line, acquires data for
a scientific
environment,
maintains
a business
application,
or
plays a game, you can create your own “living language” of words
that relate to your particular
need.
In this book we’ 11 cover
commands.
the most useful
of the standard
FORTH
All This and … Interactive!
One of FORTH’s many unique
features
is that
it lets
you
“execute
t a word by simply naming the word. If you’re working
at a terminal
keyboard,
this can be as simple as typing in the
word and pressing the RETURNkey.
11
Of course, you can also use the same word in the definition
any other word, simply by putting its name in the definition.
FORTH is called an “interactive”
language
your commands the instant you enter them.
because
it carries
of
out
We’re going to give an example that you can try yourself, showing
the process
of combining
simple commands into more powerful
commands.
We’11 use some simple FORTH words that control
your
terminal screen or printer.
But first,
let’s get acquainted
with
the mechanics
of “talking”
to FORTH through your terminal’s
keyboard.
Take a seat at your real or
imaginary
FORTH terminal.
We’11 assume that someone
has been kind enough to
set everything
up for you,
or that you have followed
all the instructions
given
for loading your particular
computer.
t
For Beginners
To “execute”
command.
a word is to order
the
computer
to carry
out a
Starting
10
Now press
FORTH
the key labeled:
RETURNt
The computer
will
respond
by saying
ok
The RETURN key is your way of telling
FORTH to acknowledge
your
request.
The ok is FORTH’s way of saying
that
it’s
done
everything
you asked it to do without any hangups.
In this case,
you didn’t
ask it to do anything,
so FORTH obediently
did nothing
and said ok.
(The ok may be either
in upper case or in lower
case, depending
on your terminal.)
Now enter
this:
15 SPACES
If you make a typing
mistake,
you can correct
it by hitting
the
“backspace”
key.
Back up to the mistake,
enter
the correct
letter,
then continue.
When you have typed the line correctly,
press the RETURN key.
(Once you press RETURN, it’s too late to
correct
the line.)
In this book, we use the symbol mm, to mark the point where you
must press
the RETURN key.
We also underline
the computer’s
output
(even though the computer
does not) to indicate
who is
typing what.
Here’s
what has happened:
15 SPACESC!ii!lmJ
________
o_k
As soon as you pressed
the return
key, FORTH printed
fifteen
blank
spaces
and then,
having
processed
your request,
it
responded
ok (at the end of the fifteen
spaces).
Now enter
this:
42 EMITmi!lmJ *ok
The phrase
“42 EMIT” tells
tFor
at Terminals
People
FORTH to print
RETURN may have a different
name on your
possib l e names are NEW LINE and ENTER.
Backspace
may also
as DEL or RUBOUT.
have
a different
an asterisk
(we’ll
terminal.
Other
name on your
terminal,
such
1 FUNDAMENTALFORTH
discuss this
the asterisk,
11
command later on in the book.)
then responded ok.
Here FORTH printed
We can put more than one command on the same line.
15 SPACES 42 EMIT 42 EMITtm!lm)
For example:
**ok
This time FORTH printed fifteen spaces and two asterisks.
A note
about entering
words and/or numbers: we can separate
them from
one another by as many spaces as we want for clarity.
But they
must be separated
by .il_ least one space for FORTH to be able to
recognize them as words and/or numbers.
Instead
of entering
the phrase
42 EMIT
over and over,
let’s
define
it as a word called
“STAR.”
Enter this
: STAR
42 EMIT ;tm!Jlm ok
Here “STAR” is the name; “42 EMIT” is the definition.
Notice
that we set off the colon and semicolon from adjacent words with
a space.
Also, to make FORTH definitions
easy for human beings
to read, we conventionally
separate
the name of a definition
from its contents with three spaces.
After
you have
entered
the
above
FORTH responds
ok, signifying
definition
and will remember it.
STARtm!Jlm
definition
and
that it has
Now enter
pressed
RETURN,
recognized
your
*ok
Voila!
FORTH executes
asterisk.
your definition
of “STAR” and prints
an
There is no difference
between a word such as STAR that you
define yourself and a word such as !EMIT! that is already defined.
In this book, however, we will put boxes around those words that
are already
defined,
so that you can more easily
tell
the
difference.
Another system-defined
word is [ID, which performs a carriage
return and line feed at your terminal.t
For example, enter this:
tFor Beginners
Be sure to distinguish
FORTHword 1£Bl.
between
the key labeled
RETURN and the
12
Starting
FORTH
CRmi!llm
ok
As you can see,
ok (on the next
Now try
FORTH executed
line).
a carriage
return,
then
printed
an
this:
CR STAR CR STAR CR STARmi!lmJ
*
T
*ok
Let’s
put a
(g]J in a definition,
like
this:
CR 30 SPACES ;mi!lmJok
: MARGIN
Now we can enter
MARGIN STAR MARGIN STAR MARGIN STARmi!lmJ
and get
left.
three
stars
lined
up vertically,
Our MARGIN STAR combination
do, so let’s define
: BLIP
will
thirty
be useful
spaces
in from the
for what we intend
to
MARGIN STAR ;mi!lmJok
We will also need
enter
the following
later chapter):
: STARS
to print
a horizontal
row of stars.
So let’s
definition
(we’ll explain
how it works in a
O DO STAR LOOP
;mi!lmJok
Now we can say
5 STARSmi!lmJ *****ok
or
35 STARSmi!llm ***********************************ok
or any number of stars
imaginable!
We will need a word which performs
stars.
Let’s define
it like this:
: BAR
MARGIN 5 STARS ;ml!llm ok
Now we can enter
BAR BLIP BAR BLIP BLIP
CR
MARGIN, then
prints
five
1 FUNDAMENTAL
FORTH
and get a letter
like this:
13
“F” (for FORTH) made up of stars.
It should look
*****
*
*****
*
*
The final step
the word “F”:
is to make this
new procedure
a word.
Let’s
call
BAR BLIP BAR BLIP BLIP CR ;CIJl!llmok
: F
You’ve just seen an example of the way simple FORTHcommands can
become the foundation
for more complex commands.
A FORTH
application,
when listed,t
consists
of a series of increasingly
powerful definitions
rather than a sequence of instructions
to be
executed in order.
To give you a sample of what a FORTH application
really
like, here’s a listing of our experimental
application:
0
1
2
3
4
5
6
7
8
(
looks
LARGE LETTER-F>
42 EMIT ;
STAR
0 DO STAR LOOP ;
STARS
CR 30 SPACES;
MARGIN
MARGIN STAR;
BLIP
MARGIN 5 STARS;
BAR
BAR BLIP BAR BLIP BLIP
F
CR
tFor Beginners
We’ll explain
Chapter 3.
more about
listing,
as it
applies
to FORTH, in
Starting
14
FORTH
The Dictionary
Each word and its definition
are
entered into FORTH’s “dictionary.”
The dictionary
already
contained
many words when you started,
but
your own words are now in the
dictionary
as well.
When you define a new word, FORTH
translates
your definition
into
dictionary
form and writes
the
entry
in the dictionary.
This
process is called “compiling. “t
: STAR
‘t2 EMIT ;
For example,
the line
: STAR
when you enter
42 EMIT ;Cll!Iim
the compiler compiles the new
definition
into the dictionary.
The compiler
does not print
the asterisk.
—
Once a word is in the dictionary,
how is it executed?
you enter the following line directly
at your terminal
a definition):
Let’s say
(not inside
STAR 30 SPACES~
This will activate
“text interpreter.”
tFor
a word called
!INTERPRET!, also
known as the
Beginners
Compilation
is a general computer term which normally means the
translation
of a high-level
program into machine code that the
computer can understand.
In FORTH it means the same thing, but
specifically
it means writing in the dictionary.
1 FUNDAMENTAL FORTH
15
The text interpreter
scans
the input stream, looking for
strings of characters
separated
by spaces.
When he finds such a string,
he looks it up in the
dictionary.
If he finds the word in the
dictionary,
he points out
the definition
to a word
called !EXECUTE!
—
–who then executes the
definition
(in this case,
he prints an asterisk).
The
interpreter
says everything’s
“ok.”
If the interpreter
cannot
find the string in the
dictionary,
he calls the
numbers-runner
(called
!NUMBER!
knows a number when
he sees one. If [NUMBER!
finds a number, he runs it
off to a temporary storage
location
for numbers.
!NUM
BER!).
16
Starting
What happens when you try to execute a word that
dictionary?
Enter this and see what happens:
FORTH
is not in the
XLERBC!lil!Im)
XLERB?
?•
When the text interpreter
cannot find XLERB in the dictionary,
it
tries to pass it off on !NUMBER!. INUMBERI shines it on. Then the
interpreter
returns the string to you with a question mark.
In some versions
of FORTH, including
polyFORTH, the compiler
does not copy the entire
name of the definition
into the
dictionary–only
the first three characters
and the number of
characters.
For example,
in polyFORTH, the text interpreter
cannot distinguish
between STAR and STAG because both words are
four characters
in length and both begin S-T-A.t
While many professional
programmers prefer the three-character
rule because
it saves memory, certain
programmers
and many
hobbyists
enjoy the freedom to choose ~ name. The FORTH-79
Standard
allows up to thirty-one
characters
of a name to be
stored in the dictionary.
To summarize:
when you type a pre-defined
it gets interpreted
and then executed.
Now remember we said
[;], as in
STAR
that~
is a word?
word at the terminal,
When you type
the word
42 EMIT ; mI!IiID
t For polyFORTH Users
The trick
to avoiding
conflicts
is to
a) be conscious of your name choices, and
when naming
a series
of similar
words,
distinguishing
character
up front, like this:
~
lLINE
2LINE 3LINE etc.
put
the
1 FUNDAMENTAL
FORTH
the following
17
occurs:
~
-.–~ ~–R —,fJ4~2—tE”[‘9a-lMI
……
T
The text interpreter
finds
the colon in the input
stream,
and oints it out to
EXECUTE.
STAR
42 EMIT
!EXECUTEjsays, “Please
start compiling.”
The compiler translates
the
definition
into dictionary
form and writes
it in the
dictionary.
When the compiler gets
to the semicolon, he
stops,
and execution returns to the
text interpreter,
who gives
the message ok.
18
Starting
FORTH
Say What?
In FORTH, a word is a character
or group of characters
that have
a definition.
Almost any characters
can be used in naming a
word. The only characters
that cannot be used are:
return
because
finished
backspace
because
the computer
thinks
to correct
a typing error,
space
because the computer
the word, and
rt
caret
or A)
because
thinks
discuss
the
computer
entering,t
thinks
thinks
you’ve
you’re
it’s
the
trying
end of
the editor
(if you ‘re using
it)
you mean something
else.
We’ll
the editor
in Chap. 3.
Here is a FORTH word whose name consists
of two punctuation
marks.
The word is ~ and is pronounced
dot-quote.
You can use
G::] inside
a definitiont
to type
a “string”
of text
at your
terminal.
Here’s an example:
GREET
. ” HELLO, I SPEAK FORTH ” ;mmlm ok
We’ve just defined
a word called
GREET. Its definition
consists
of just one FORTH word, G::], followed
by the text we want typed.
The quotation
mark at the end of the text will not be typed;
it
marks the end of the text.
It’s called
a “delimiter.”
tFor
Philosophers
No, the
better
grounds
bulb.”
it needs
So let’s
computer
doesn’t
“think.”
Unfortunately,
there’s
no
word for what it really
does.
We say “think”
on the
that it’s all right
to say, “the lamp needs a new light
Whether the lamp really
needs a bulb depends
on whether
to provide
light
(that is, incandescence
is its karma).
just say the computer thinks.
tFORTH-79 Standard
In systems
of a colon
that conform to the
definition
as well.
Standard,
~ will
execute
outside
1 FUNDAMENTAL
FORTH
When entering
the definition
Ii] to end the definition.
Let’s execute
of GREET, don’t
forget
the closing
GREET:
GREETmI!ill3
The Stack:
19
HELLO, I SPEAK FORTH ok
FORTH’s Worksite for Arithmetic
A computer would not be much good if it couldn’t do arithmetic.
If you’ve never studied
computers before,
it may seem pretty
amazing that a computer (or even a pocket calculator)
can do
arithmetic
at all.
We can’t cite all the mechanics in this book,
but believe us, it’s not a miracle.
In general,
computers
perform their
operations
by breaking
everything
they do into ridiculously
tiny pieces of information
and ridiculously
easy things to do. To you and me, “3 + 4” is
just “7,” without
even thinking.
To a computer,
“3 + 4” is
actually a very long list of things to do and remember.
Without getting
too specific,
let’s
say you have a pocket
calculator
which expects its buttons to be pushed in this order:
in order to perform the addition and display
generalized
picture of what might occur:
the result.
Here’s a
Name of Next
Operation
–the
number 3 goes into one place
(called
Box A).
Name of Next
Operation
+
–the
intended
opera t ion (addition)
is remembered somehow.
20
Starting
FORTH
Name of Next
Operation
+
–the
number 4 is stored
into
a second
place
(called
Box B).
Name of Next
Operation
–the calculator
“Next Operation”
leaves the result
performs
the operation
that
Box on the contents
of the
in Box A.
is stored
in the
number boxes and
Many calculators
and computers approach arithmetic
problems in a
way similar
to what we’ve just described.
You may not be aware
of it, but these machines are actually
storing
numbers in various
locations
and then performing operations
on them.
In FORTH, there
is one central
location
where numbers
temporarily
stored before being operated
on. That location
called
the “stack.”
Numbers are “pushed onto the stack,”
then operations
work on the numbers on the stack.
The best way to explain
enter the following line
here’s
what happens,
the stack is to illustrate
at your terminal:
it.
are
is
and
If you
key by key.
Recall that when you enter a number at your terminal,
the text
interpreter
hands it over to INUMBERI, who runs it to some
location.
That location,
it can now be told, is the stack.
In
short,
when you enter the number three from the terminal,
you
push it onto the stack.
21
1 FUNDAMENTAL FORTH
Now the four goes
three downward.
onto
the
“top”
of the
stack
and pushes
the
,,
The next word in the input stream can be found in the dictionary.
l±Jhas been previously defined to~ake the top two numbers off
the stack, add them, and push the result back onto the stack.”
22
Starting
The next word, G], is also found in the dictionary.
previously
defined
to take the number off the stack
at the terminal.
Postfix
FORTH
It has been
and print
it
Power
Now wait,
you say.
Why does
FORTH want you to type
3 4 +
instead
of
3
which
+
4
is more familiar
to most people?
FORTH uses “postfix”
notation
(so called
because
the operator
is
affixed
after
the numbers)
rather
than
“infix”
notation
(so
called
because the operator
is affixed
in-between
the numbers) so
that all words which “need” numbers can get them from the stack. t
tFor
Pocket-calculator
Hewlett-Packard
Experts
calculators
feature
a stack
and postfix
arithmetic.
1 FUNDAMENTAL
FORTH
23
For example:
the word
l±]gets
the word GJgets
two numbers from the stack
one number from the stack
the word !SPACES! gets
that many spaces;
one number from the
the word !EMIT! gets a number that
prints that character;
represents
and adds them;
and prints
stack
it;
and prints
a character
even the word STARS, which we defined
ourselves,
number from the stack and prints that many stars.
and
gets
a
When all operators
are defined
to work on the values that are
already
on the stack,
interaction
between
many operations
remains simple even when the program gets complex.
Earlier
we pointed
out that FORTH lets you execute
a word in
either of two ways: by simply naming it, or by putting
it in the
definition
of another word and naming that word. Postfix is part
of what makes this possible.
-Just as an example,
let’s
suppose
we wanted a word that will
always add the number 4 to whatever
number is on the stack (for
no other purpose than to illustrate
our point).
Let’s call the
word
FOUR- MORE
We could define
it this
way:
: FOUR-MORE 4 + ; Cii!lm)
and test
it this
way:
3 FOUR-MORE.Cii!lm)~
and again:
-10 FOUR-MORE,Cii!lm) -6 ok
The 11 4 11 inside
the definition
goes onto the stack, just as it
would if it wete outside a definition.
Then the [3 adds the two
numbers on the stack.
Since [±I always works on the stack,
it
doesn’t care that the “4” came from inside the definition
and the
three from outside.
As we begin to give some more complicated
examples, the value of
the stack and of postfix
arithmetic
will become increasingly
apparent
to you. The more operators
that are involved,
the more
important
it is that they all be able to “communicate”
with each
other,
24
Starting
Keep Track
FORTH
of Your Stack
We’ve just beg .un to demonstrate
the philosophy
behind the stack
and postfix
notation.
Before
we continue,
however,
let’s
look
more closely
at the stack
in action
and get accustomed
to its
peculiarities.
FORTH’s stack is described
as “last-in,
first-out”
(LIFO). You
see from the earlier
illustration
why this is so. The three
pushed onto the stack first,
then the four pushed on top of
Later the adding machine
took the four off first
because
it
on top.
Hence “last-in,
first-out.”
can
was
it.
was
In general,
the only accessible
value at any given time is the
top value.
Let’s
use another
cu>eration,
the GJto further
demonstrate.
Remember that each W removes one number from the
stack and prints
it.
Four dots, therefore,
remove four numbers
and print them.
2 4 6 8 • • • .ll!Iim
The system
in turn.
reads
input
8 6 4 2 ok
from left
For input, the rightmost
top of the stack.
For output,
the rightmost
bottom of the stack.
Let’s
see what kind of trouble
to right
value
value
and executes
on the
on the
screen
screen
we can get outselves
10 20 30 ••••
(that’s
four dots)
then
RETURN. What you get
is:
will
each
word
end up on
came from the
into.
Type:
1 FUNDAMENTALFORTH
10 20 30 • • .
25
.cmmJ 30
Each dot removes one value.
no value left on the stack
you so.
This error
is called
“stack
underflow
is not “ok. “)
The opposite
condition,
called
“stack overflow.
condition
should never
terribly
wrong.
11
20 10 0 • STACK EMPTYt
The fourth dot found that there was
to send to the terminal,
and it told
underflow.”
(Notice
that
a stack
when the stack completely
fills
up, is
The stack is so deep, however, that this
occur except when you’ve done something
It’s important
to keep track of new words’ “stack effects”;
that
is, the sort of numbers a word needs to have on the stack before
you execute
it, and the sort of numbers it will leave on the stack
afterwards.
If you maintain
a list of your newly created
words with their
meanings as you go, you or anyone else can easily understand
the
words’ operations.
In FORTH, such a list is called
a “glossary.”
To communicate
stack effects
in a visual way, FORTH programmers
conventionally
use a special
stack notation
in their
gl ossaries
or tables
of words.
We’re introducing
the stack notation
now so
that you’ll
have it under your belt when you begin
the next
chapter.
tFor
the Curious
Actually,
dot always prints whatever
is on the top, so if there is
nothing
on the stack, it prints
whatever
is just below the stack,
which is usually
zero.
Only then is the error
detected;
the
offending
word (in this case dot) is returned
to the screen,
followed by the “error message.”
26
Starting
Here’s
the basic
(before
–
FORTH
form:
after)
The dash separates
the things that should be on the stack (before
you execute
the word) from the things
that will be left there
afterwards.
For example, here’s the stack notation
for the word
G]:
(n —
)
(The letter
“n” stands for “number.”)
This shows that G) expects
one number on the stack
(before)
and leaves
_!!.£ number
on the
stack (after).
Here’s
the stack
+
notation
for the word
[3.
(nl n2 — sum)
.When there
is more than one n, we number them nl, n2, n3, etc.,
consecutively.
The numbers l and 2 do not refer to position
on
the stack.
Stack position
is indicated
by the order in which the
items are written;
the rightmost
item on either
side of the arrow
is the topmost
item on the stack.
For example,
in the stack
notation
of [±], the n2 is on top:
+
(nl n2 — sum)
You’re the top
Since you probably
have the hang of it by now, we’ll be leaving
out thecmmI:)symbol
except where we feel it’s needed for clarity.
You can usually
tell
where
to press
“return”
because
the
computer’s
response
is always underlined.
1 FUNDAMENTAL
FORTH
27
Here’s a list of the FORTH words you’ve lear ned so far, including
their stack notations
( 11 n II stands for number; 11 c II stands
for
character):
—
)
Creates a new definition
the name xxx, consisting
word or words yyy.
—
)
Performs a carriage
return
line feed at your terminal.
(n —
)
Prints
the given
number of
blank spaces at your termina l .
)
Prints one blank space
terminal.
at your
(C —
)
Transmits
a character
output device.
to the
—
)
Prints
the character
xxx at your terminal.
character
terminates
string.
string
The
the
yyy
XXX
CR
SPACES
—
SPACE
EMIT
11
xxx
11
+
(nl n2 — sum)
(n —
)
we’ll talk
arithmetic.
and
11
Adds.
Prints
one
In the next chapter
perform some fancier
with
of
a number,
followed
by
space.
about
getting
the
computer
to
Review of Terms
Compile
to generate
a dictionary
entry in computer
memory from source text (the written-out
form
of a definition).
Distinct from “execute.”
Dictionary
in FORTH, a list
of words and definitions
including
both
“system”
definitions
(predefined)
and “user” definitions
(which you
inven~.
A dictionary
resides
in computer
memory in compiled form.
28
Starting
FORTH
Execute
to perform.
Specifically,
to execute
to perform
the operations
specified
compiled definition
of the word.
a word is
in the
Extensibility
a characteristic
of a computer
language
which
allows
a programmer
to add new features
or
modify existing
ones.
Glossary
a list of words defined
in FORTH, showing their
stack effects
and an explanation
of what they
do,
which
serves
as a reference
for
programmers.
Infix
notation
the method of writing
operators
between
operands
they affect,
as in “2 + 5.”
Input
stream
the text to be read by the text interpreter.
This may be text that you have just typed in at
your terminal,
or it may be text that is stored
on disk.
the
Interpret
(when referring
to FORTH’s text interpreter)
to
read the input stream,
then to find each word
in the dictionary
or, failing
that,
to convert
it to a number.
LIFO
(last-in,
first-out)
the type of stack
which
FORTH uses.
A can of tennis
balls
is a LIFO
structure:
the last ball you drop in is the one
you must remove first.
Postfix
notation
Stack
the method
of writing
operators
after
the
operands
they affect,
as in “2 5 +” for “2 + 5.”
Also known as Reverse Polish Notation.
in FORTH, a region
of memory
which
is
controlled
in such a way that
data
can be
stored or removed in a last-in,
first – out (LIFO)
fashion.
Stack
overflow
the error condition
that occurs when the entire
area
of memory
allowed
for the
stack
is
completely
filled
with data.
Stack
underflow
the error
condition
that
occurs
operation
expects
a value on the
there is no valid data on the stack.
Word
in FORTH, the name of a definition.
when
stack,
an
but
29
1 FUNDAMENTAL
FORTH
Problems
Note:
rules:
–
Chapter
before
1
you work these
problems,
remember
these
simple
needs a Ii].
Every~
and
Every
1.
[:l
needs a
[:f.
Define a word called
GIFT which, when executed,
will
out the name of some gift.
For example, you might try:
: GIFT
type
. II BOOKENDSII
Now define
a word called
GIVER which will print
out a
person’s
first name. Finally,
define a word called
THANKS
which includes
the new FORTH words GIFT and GIVER, and
prints out a message something like this:
DEAR STEPHANIE,
THANKSFOR THE BOOKENDS.ok
2.
3.
Define
a word
stack,
(Hint:
subtracts
teP,r and returns
you can use ~-)
called
TEN.LESS
which
the
takes
a number
answer
on the
on the stack.
After entering
the words in Prob. 1, enter a new definition
for GIVER to print someone else’s name, then execute THANKS
again.
Can you explain why THANKSstill prints out the first
giver’s name?
2
HOW TO GET RESULTS
In this chapter,
we’ll dive right into some specifics
that you
need to know before we go on. Specifically,
we ’11 introduce some
G and some special
of the arithmetic
instructions
besides
operators
for rearranging
the order of numbers on the stack, so
that you’ll be able to write mathematical
equations in FORTH.
FORTH Arithmetic
Here are
FORTH:t
the
— Calculator
four
simplest
.————–
+
*
I
Style
integer-arithmetic
– —-(nl
(nl
(nl
(nl
n2
n2
n2
n2
—–
sum)
diff)
prod)
quot)
operators
in
— —–~p~r_,onounced:
Adds.
Subtracts (nl-n2).
Multiplies.
Divides (nl/n2).
Unlike calculators,
computer terminals
don’t have
special
keys for multiplication
and division.
Instead we use ~ and [2].
tif
Math Is Not Your Thing
Don’t worry if this chapter
looks a little
like an algebra
textbook.
Solving math problems is only one of the things you
can do with FORTH. Later we’ll explore some of the other things
FORTHcan do.
Meanwhile,
we’d
numbers, such as:
… -3, -2, -1,
like
to remind
o, 1,
2, 3, …
you that
integers
are
whole
Integer arithmetic
(logically
enough) is arithmetic
that concerns
itself only with integers,
not with decimal-point
numbers, such as
2.71.
31
Starting
32
FORTH
In the first chapter,
we learned
that we can add two numbers by
putting
them both on the stack, then executing
the word [±1,then
finally
executing
the word G) (dot) to get the result
printed
at
our terminal.
17 5 + . 22 ok
We can use this method with all of FORTH’s arithmetic
operators.
In other
words,
we can use FORTH like
a calculator
to get
answers,
even without writing
a “program. 11 Try a multiplication
problem:
7 8
*.
56 ok
By now we’ve seen that the operator
comes after the numbers.
In
the case
of subtraction
and division,
though,
we must also
consider
the order of numbers (“7 – 4” is not the same as “4 – 7”).
Just remember
this
rule:
To convert
to postfix,
of the expression:
Infix
3
…–:r-‘+
500 ~-
6 X5
6~*
20 / 4
20~
type
74-.~
3
500 – 300
subtraction
7 – 4 =
in
move the
Postfix
+4
So to do this
simply
simply
problem:
operator
to the
end
33
2 HOWTO GET RESULTS
For Adventuresome
Newcomers
Sitting
at a Terminal
If you’re one of those people who likes to fool around and figure
things
out for themselves
without
reading
the book, then you’re
bound to discover
a couple of weird things.
First off, as we told
you, these operators
are integer
operators.
That not only means
that you can’t do calculations
with decimal values, like
10.00 2.25 +
it also
means that
21 4 / .~
Another
instead
thing
10000 10
you can only
is that
of
get
integer
results,
as in
5.25 ok
if you try
to multiply:
*
or some such large numbers, you’ll
get a crazy answer.
So we’re
telling
you up front
that with the operators
introduced
so far
and with G] to print the results,
you can’t have any numbers that
are higher
than 32767 or lower than -32768.
Numbers within this
range are called
“single-length
signed numbers.”
l
+3276J
Allowable
numbers.
range
of
single-length
signed
-32768~
Notice,
in the list of FORTH words a few pages back, the letter
“n,” which stands for “number.”
Since FORTH uses single-length
numbers more often than other types of numbers, the “n” signifies
that the number must be single-length.
And yes, there are other
operators
that extend
this range
(“double-length”
operators,
which are indicated
by “d “).
All of these
mysteries
will
be explained
in time,
so stay
tuned.
34
Starting
The order
problem:
of numbers
stays
the
same.
Let’s
try
FORTH
a division
204/.~
The word [Z] is defined
by the top number:
What do you do if
expession,
like:
*
4 + (17
to divide
you
have
the second
more
and here’s
*
one
operator
in an
12)
you ask? Let’s take it step-by-step:
first multiply seventeen
by twelve,
you would write:
17 12
than
number on the stack
4 +
why:
208 ok
the parentheses
then add four.
tell you to
So in FORTH
35
2 HOW TO GET RESULTS
17 and 12 go onto
result.
the
stack.
l!l
multiplies
them and returns
Then the four goes onto the stack, on top of the 204. [±I rolls
the adding machine and adds them together,
returning
only
result.
Or suppose
like this:
you want to add five
numbers.
the
out
the
You can do it in FORTH
Starting
36
17 20 + 132 + 3 + 9 +.
FORTH
181 ok
17
3
Now here’s
(3+9)
an interesting
*
problem:
(4+6)
To solve it we have to add three to nine first, then add four to
six, then finally
multiply the two sums. In FORTH, we can write
3 9 + 4 6 +
and here’s
‘
3
* .
120 ok
what happens:
6
4
12
Notice that we very conveniently
saved the sum twelve on the
stack while we went on about the business of adding four to six.
Remember that we’re not concerned
yet with writing
We are simply using FORTH as a calculator.
definitions.
If you’re like most beginners,
you probably would like to try your
hand at a few practice
problems until you feel more comfortable
with postfix.
2 HOWTO GET RESULTS
Postfix
Practice
Convert
style.”
the following
For example,
ab+
37
Problems
(Quizzie
infix
2-a)
equations
to postfix
expressions
to infix:
“calculator
C
would become
*
a b
+
C
1.
c(a + b)
2.
3a – b
+
4
t3.
C
0.5 ab
100
4.
n + 1
n
5.
x(7x + 5)
Convert
the following
6.
a b – b a + /
7.
a b 10
tFor
Beginners
Remember,
be clever.
postfix
*/
we’re
only
using
integer
arithmetic,
qo1
e
“L
e + q
q–=—e ·9
.lO
so you’ll
I ooz ,,. q e
/ Z / 001 ,,. q e
“€
e €
·z
+ q e o
+ q e
·t
+o/v-q,,.
¥-
¥- X
+ £
I
¥-
XL
u + t u
‘£
·v
have
.lO
e-z a1zz1no
¥- 0
s.:i:a~suv
to
Starting
38
FORTH Arithmetic
— Definition
Style
•
•• W
m,
In Chap. 1 we saw that we could
define
new words
in terms
of
numbers
and other
pre-defined
words.
Let’s explore
some further
possibilities,
using some of our
newly-learned
math operators.
Let’s say we want to convert
know that
1 yard
36 inches
1 foot=
12 inches
FORTH
various
measurements
to inches.
We
and
so we can define
these
two words:
YARDS>IN 36 * ; ok
FT>IN 12 * ; ck-where the names symbolize
“yards-to-inches”
inches.”
Here’s what they do:
and
“feet-to-
10 YARDS>IN• 360 ok
2 FT>IN . 24 ok
If we always want our result
to be in inches,
we can define:
YARDS 36 * ; ok
FEET 12 * ; ~
INCHES;~
-so that
we can use the phrase
10 YARDS2 FEET+ 9 INCHES+.
393 ok
Notice that the word INCHES doesn’t
do anything
except remind
If we really
want to
the human user what the nine is there for.
get fancy, we can add these three definitions:
YARD YARDS; ok
FOOT FEET; ck°
INCH;~
-so that the user can enter the singular
nouns and still get the same result:
form of any of these
2 HOW TO GET RESULTS
39
1 YARD 2 FEET + 1 INCH +
2 YARDS 1 FOOT + • 84 ok
•
61 ok
So far we have only defin e d words whose definitions
contain
a
single math operator.
But it’s perfec tl y possi b l e to put many
op e r a tors inside a defi ni t i on , if that’s what you need to do.
Let’s sa y we want a word that c omput es the sum of five numbe r s on
the stac k. A few pages back we summed five numbers like this:
17 20 + 132 + 3 + 9 + . 181 ok
But we can also enter
17 20 132 3 9 + + + +
.
181 ok
132
17
5
132
3.
20
131
q
‘
3
17
132
10
17
[±]
EB
[±)
12
14+
132
20
20
17
[J~
17
We get the same answer, even though we’ve clustered
all the
numbers into one group and all the operators
into another group.
We can write our defi nition like this:
: 5#SUM
and execute
+ + + + ; ok
it like this:
Starting
40
FORTH
17 20 132 3 9 5#SUM • 181 ok
we were going to keep 5#SUM for future use, we could enter it
into our ever-growing
glossary,
along
with a note that
it
“expects
five arguments”t
on the stack,
which it will add
together.
If
Here’s
another
(a
+
b)
equation
*
to write
for:+
expression
can
+
C
As we saw in Quizzie
postfix as
C
a definition
2-a,
this
be written
in
a b + *
Thus we could write
: SOLUTION
our definition
+ *;
ok
as long as we make sure that
order:
we enter
the arguments
in the proper
c a b SOLUTION
tFor
Semantic
Freaks
In mathematics,
variable
the
word “argument”
o~ a function.
Computer
refers
linguists
term to refer to numbers being operated
have also borrowed the word “parameters”
the same thing.
to an independent
have
borrowed
on by operators.
to describe
pretty
this
They
much
tFor Beginners Who Like
Word-problems
If a jet
plane
flies
at an
average air speed of 600 mph and
if it flies with a tail wind of 25
mph, how far will it travel
in
five hours?
If
we define
: FLIGHT-DISTANCE
+
*
we could enter
5 600 25 FLIGHT-DISTANCE . 3125 ok
Try it with
values).
different
values,
inc~uding
head
winds
(negative
41
2 HOW TO GET RESULTS
Definition-style
Practice
Problems
(Quizzie
2-b)
Convert
the following
infix expressions
into FORTH definitions
and show the stack order required
by your definitions.
Since
this is Quizzie 2-b, you can name your definitions
2B1, 2B2, etc.
For example,
1.
ab+
would become
C
which expects
2.
3.
a – 4b
6
+
this
stack
: 2B1
order:
* + ;
(c b a –
result)
C
a
Sb
4.
0.5 ab
100
5.
a(2a + 3)
6.
a – b
C
11 1 aM qo1qM SlO:}eJado
~sea1 ~e–j:}q6p
aJ,nol
·l1:}Joqs lJah aonpoJ:}U1
uo1:}e1nd1uew
~Oe:}s aq:} :}noq~1M
‘a1q1ssodw1
s,auo s1q:} p1es nol n
(:}1nsal —
,,. +
£
,,.
I ooc:..
q e)
q e)
I ,,. a
me: :
(Hnsa:i – q e o)
9 – “‘ v zs:c::
I
·s
vs:c:: ·v
(:}1nsaJ !
+
e e)
c: ss:c::
(:}1nsaJ -!
•9
“£
·c:
42
Starting
The Division
FORTH
Operators
division
operator.
Slash
The word 12[is FORTH’s simplest
only the quotient;
any remainder
is lost.
If you type:
supplies
224/.~
you get only
If you’re
operator,
the quotient
thinking
then five
five,
not the remainder
of a pocket
calculator’s
is not the full answer.
two.
per-cent
division
operators
supplied
by
But 12] is only one of several
FORTH to give you the flexibility
to tell the computer
exactly
what you want it to do.
For example, let’s say you want to solve this problem:
“How many
dollar
bills
can I get in exchange
for 22 quarters?”
The real
answer, of course,
is exactly
5, not S.S. A computerized
money
changer,
for example,
would not know how to give you 5.5 dollar
bills.
Here are two more FORTH division
operators:
/MOD
(ul u2 -u-rem u-quot)
Divides.
Returns
the remainder
and quotient.
MOD
(ul u2 — u-rem)
Returns the
remainder
from
division.
The “u” stands
for “unsigned.”
We’ll see what this~
means in the chapter
on computer
numbers.
For now
though, it means that the numbers can’t be negative.
.
~
I/MODI gives both the remainder
and the quotient;
!MODIgives the
remainder
only.t
(For I/MODI, the stack notation
in the table
indicates
that the quotient
will be on the top of the stack, and
the remainder
below . Remember,
the rightmost
represents
the
topmost.)
tFor
the Curious
MOD refers
“remainder.”
to
the
term
“modulo,”
which
basically
means
2 HOWTO GETRESULTS
Let’s try the first
43
one:
22 4 /MOD • • 5 2
ok
Here i/MODl performs the division
and puts both the quotient
and
the remainder
on the stack.
The first dot prints the quotient
because the quotient was on top.
~”ttuf(~JVMODI(i;IHh’s
older brother)
I
·~sh~
.·
With what we’ve learned
: QUARTERS
So that
so far, we can easily
4 /MOD •
•
11
ONES AND
11
define
II
this word:
QUARTERS
II
;
you can type:
22 QUARTERS
with this
result:
22 QUARTERS 5 ONES AND 2 QUARTERS
The second word in the table,
For example in:
22 4 MOD • 2 ok
the two is the remainder.
iMOD!,
ok
leaves
only
the remainder.
Starting
44
FORTH
Stack Maneuvers
If you worked
infix
equation
Prob.
6 in the
last
set,
you discovered
that
the
a – b
C
cannot be solved with a definition
rearrange
values on the stack.
Well, there is a way:
called !SWAPj:-
by using
unless
a “stack
there
is some way to
manipulation
operator”
!SWAP!
The word !SWAP! is defined
stack i terns:
to switch
the
order
As with the other stack manipulation
operators,
!SWAP!at your terminal
in “calculator
style”;
that
have to be contained
within a definition.
of the
top
two
you can test
is, it doesn’t
45
2 HOW TO GET RESULTS
First
enter
l 2 ••
then
2 l ok
again,
this
time with iSWAPj:
1 2 SWAP • • 1 2 ok
Thus Prob.
6 can be solved
with this
phrase:
– SWAP/
with
(c a b
Let’s
give
a=
then
) on the stack.
a, b, and c these
10
b = 4
C
put them on the stack
test
values:
=2
and execute
the phrase,
like
so:
2 10 4 – SWAP / .~
Here is a list
iSWAPj.
of several
stack
manipulation
including
SWAP
(nl n2 –
DUP
(n — n n)
OVER
(nl n2 –
ROT
(nl n2 n3 — n~ n3 nl)
Rotates
the third
item to the top.
DROP
(n —
Discards
the
stack item.
)
n2 nl)
operators,
Reverses
two stack
Duplicates
stack item.
nl n2 nl)
the top—=-items.
the
top
Makes
a copy
of
the
second
item
and pushes
it on
top.
top
Starting
46
FORTH
The next stack manipulation
operator
on the list, IDUPI, simply
makes a second copy (duplicate) of the top stack item.
For example, if we have “a” on the stack, we can compute:
a2
as follows:
DUP *
in which the following
steps occur:
Contents
Operation
-of -Stack
-a
DUP
a a
*
a2
2 HOWTO GET-RESULTS
Now somebody
a
given
*
(a
tells
+
you to evaluate
–
the expression:
b)
the following
(ab
47
stack
order:
)
But, you say, I’m going to need a new manipulation
operator:
I
want two copies of the “a,” and the “a” is under the “b.”
Here’s
the word you need:
loVERI. !OVER\ simply makes a copy of the “a”
and leapfrogs
it~
the “b”:
(ab
— a~a)
Now the expression:
a
*
(a + b)
can easily
be written:
OVER+ *
Here’s
what happens:
Contents
of Stack
OEeration
a b
OVER
a b a
+
a (b+a)
*
a*(b+a)
When writing
equations
in FORTH, it’s best to “factor
first.
For example, if somebody asks you to evaluate:
them out”
a 2 + ab
in FORTH, you’ll
find it quite
complicated
impossible)
using the words we’ve introduced
factor out the expression
to read:
a
which
*
(a
+
(and maybe even
so far .•. unless you
b)
is the expression
we just
evaluated
so easily.
48
Starting
FORTH
The fourth stack manipulator on the list is !ROTi (uro ounced
rote), which is short for “rotate.”
Here’s what ROT does to the
top three stack values:
1
For example, if we need to
evaluate the expression:
ab – be
we should first
b
*
factor
out the “b”s:
(a – c)
Now if our starting-stack
order
is this:
(c b a —
we can use:
ROT –
*
in which the following
steps
will occur:
2 HOWTO GET RESULTS
Operation
Contents
of Stack
—C
ROT
49
b a
b a
C
b (a-c)
(b* (a-c))
*
The final stack manipulation
operator
it does is discard the top stack value.
Pretty
simple,
huh?
on the list
is !DROPj. All
We’ll see some good uses for !DROP!later
on.
Starting
50
FORTH
A Handy Hint
A Non-destructive
Stack
Print
Beginners
who are just learning
to manipulate
numbers on the
stack in useful ways very often find themselves typing a series of
dots to see what’s on the stack after their manipulations.
The
problem with dots, though, is that they don’t leave the numbers
on the stack for future manipulations.
Here is the definition
of a very useful word for such beginners •
• sprints
out all the values
that happen
to be on the stack
“non-destructively”;
that is, without removing them.
Type the
definition
in as shown here, and don’t worry about how it works.
CR ‘S SO @ 2- DO I
: .S
Let’s
test
it,
first
with nothing
@ •
-2 +LOOP ;~
on the stack:
.s
0 Ole
you can see, in this version
for the
number as a reference
As
same
number
we see
when
we type
of .s, we always see at least one
bottom of the stack; that is, the
a
Q and
•cmmm’—o
__ S_T_A_C_K_E_M_P_T_Y
Now let’s
try it with numbers on the stack:
1 2 3 .s
0 1 2 3 ok
ROT .S
0 2 3 1 olc
get
2 HOWTO GET RESULTS
Stack
1.
Manipulation
3.
Write
jovERj.
becomes
C
a phrase
that
C
does
Write a definition
called
stack items in the opposite
a b
the
for
4.
n + 1
–n
(n –
result)
5.
x(7x + 5)
(x —
result)
6.
9a 2 – ba
(a b — result)
lO
!
!
I
+
without
rotates
the top three
from [ROT!; that is,
equations,
given
,,. 6 R:3:1\.O
9::>Z
·9
,,. Lana
S:::>Z
·s
v:::>Z
v::>Z
·v
s
I avMs +1 ana
dVM.S
+
using
a b
following
,,. – dVM.S
! ,,.
!OVER! does,
direction
Write definitions
effects
shown:
leaving
b a
what
C
2-c)
items on the stack,
that is,
ana
dVMS
.LOR dVM.S
·t
·z
·1
o-z a1zz1no- sla~suv
the
stack
Starting
52
Playing
FORTH
Doublest
The next
familiar:
four
stack
manipulation
operators
(dl d2 — d2 dl)
Reverses
two pairs
hers.
2DUP
(d — d d)
Duplicates
the top
pair of numbers.
2OVER
(dl d2 — dl d2 dl)
of
a copy
Makes
the second pair of
numbers and pushes
it on top.
2DROP
(d —
Discards
the top
pair of numbers.
listed
we won’t
vaguely
~;
~
The prefix
“2” indicates
that these
stack manipulation
operators
handle
numbers in pairs. t The letter
“d” in
the stack
effects
column stands
for
“double.”
“Double”
has a special
significance
that we will discuss when
we discuss “n” and “u.”
The “2”-manipulators
so straightforward,
you with examples.
look
top
num-
2SWAP
)
the
of
should
above are
even bore
One more thing:
there are still
some
stack manipulators
we haven’t
talked
about yet, so don’t go crazy by trying
too much fancy footwork on the stack.
Guess
who.
tFORTH-79 ” Standard
These
which
+
+ For
words are part of the Standard’s
is optional
in a Standard
system.
“Double Number Word Set,”
j2ROT! is included.
Old Hands
They can also
be used to handle
double-length
(32-bit)
numbers.
2 HOWTO GET RESULTS
53
Here’s a list of the FORTH
words we’ve covered in this chapter:
+
{nl n2 –
sum)
Adds.
{nl n2 — diff)
Subtracts
*
I
{nl n2 — prod)
Multiplies.
{nl n2 — quot)
Divides
/MOD
(ul u2 -u-rem u-quot)
Divides.
remainder
MOD
(ul u2 – – u-rem)
Returns
division.
SWAP
(nl n2 — n2 nl)
Reverses
items.
DUP
{n —
Duplicates
item.
OVER
(nl n2 -nl n2 nl)
Makes a copy of the second
item and pushes it on top.
ROT
(nl n2 n3 —
Rotates
the
top.
n n)
n2 n3 nl)
Discards
item.
(nl-n2).
(nl/n2).
Returns the
and quotient.
the
remainder
the
top
two stack
the
the
top
third
the
from
stack
item
top
to
stack
DROP
(n —
2SWAP
(dl d2 — d2 dl)
Reverses
the
of numbers.
2DUP
(d — d d)
Duplicates
numbers.
2OVER
(dl d2 -dl d2 dl)
Makes a copy of the second
pair of numbers and pushes
it on top.
2DROP
(d —
Discards
numbers.
)
)
the
the
top
two pairs
top pairs
top
pair
of
of
Starting
54
FORTH
Review of Terms
Double-length
numbers
Single-length
numbers
integers
billion
introduce
which encompass a range of over -2
to +2 billion
(and which
we’ll
officially
in Chap. 7).
integers
which fall within the range of -3276&
to +32767: the only numbers which are valid as
the arguments
or results
of any of the
operators
we’ve
discussed
so far.
(This
seemingly arbitrary
range comes from the way
computers are designed( as we’ll see later on.)
2 HOWTO GETRESULTS
Problems — Chapter
55
2
(answers in the back of the book)
1.
What is the difference
between !DUPjjDUPjand j2DUPI?
2.
Write a phrase which will reverse
items on the stack: that is,
the order
of the top four
(l 2 3 4 — 4 3 2 l)
3.
Write a definition
called 3DUP which will duplicate
three numbers on the stack: for example,
(l 2 3 –
l 2 3 l 2 3)
Write definitions
for the following
stack effects shown:
4.
5.
6.
a2
the top
+ ab + c
a – b
a+b
infix
equations,
given
the
(c a b — result)
(a b — result)
Write a set of words to compute prison
sentences
hardened criminals such that the judge can enter:
for
CONVICTED-OFARSONHOMICIDETAX-EVASIONok
WILL-SERVE 35 YEARSok
-or any series
of crimes
CONVICTED-OF and ending
sentences:
HOMICIDE
ARSON
BOOKMAKING
TAX- EVASION
7.
20
10
2
5
beginning
with
with WILL-SERVE.
the word
Use these
years
years
years
years
You’re the inventory
programmer
at Maria’s
Egg Ranch.
Define a word called EGG.CARTONS
which expects on the stack
the total number of eggs laid by the chickens
today and
prints out the number of cartons that can be filled with a
dozen each, as well as the number of left-over eggs.
3
THE EDITOR (AND STAFF)
Up till
now you’ve
been compiling
new definitions
dictionary
by typing
them at your terminal.
This
introduces
an alternate
method, using disk storage.
Let’s begin
dictionary.
Another
with some observations
Look at the
that
specifically
into the
chapter
concern
the
Dictionary
If you’ve been experimenting
at a real
have discovered
some things
we haven’t
case, it’s time to mention them.
live terminal,
mentioned
yet.
you may
In any
Discovery
One: You can define
the same word more than once
in different
ways–only
the most recent
definition
will be
executed.
For example,
if you have
: GREET
then
you should
entered:
• ” HELLO. I SPEAK FORTH. ” ; ok
get this
GREET HELLO.
result:
I SPEAK FORTH. ok
and if you redefine:
: GREET
• II HI THEREI
you get the most recent
II
;—2.!5_
definition:
GREET HI THERE! ok
Has the first
GREET been erased?
No, it’s still
there,
but the
most recent
GREET is executed
because of the search order.
The
text interpreter
always starts
at the “back of the dictionary”
where the most recent
entry is.
The definition
he finds first is
the one you defined last.
This is the one he shows to !EXECUTE!.
57
58
Starting
We can prove that
the old GREET is still
there.
FORTH
Try this:
FORGETGREET ok
and
GREET HELLO. I SPEAK FORTH. ok
(the old GREET again!)
The word !FORGET!looks up the given word in the dictionary
and,
in effect, removes it from the dictionar
along with anything you
may have defined since that word. FORGET, like the interpreter,
searches
starting
from the back; he only removes
the most
recently
defined version of the word (along with any words that
follow).
So now when you type GREET at the terminal,
the
interpreter
finds the original
GREET.
!FORGET! is a good word to know; he helps you to weed out your
dictionary
so it won’t overflow.
(The dictionary
takes up memory
space, so as with any other use of memory, you want to conserve
it.)
Discovery Two: When you enter definitions
from the terminal
(as you have been doing), your source text t is not saved.
Only the compiled
form of your definition
is saved
in the die-
tFor Beginners
The “source
as:
text”
is the original
version
of the definition,
: FOUR-MORE 4 + ;
which the compiler
translates
into a dictionary
entry.
such
59
3 THE EDITOR (ANDSTAFF)
tionary.
So, what if you want to make a minor change to a word
you’ve already defined?
This is where the EDITOR comes in. With
the EDITOR, you can save your source text and modify it if you
want to.
The EDITOR stores your source text on disk.
So before we can
really discuss the EDITOR, we’d better introduce the disk and the
way the FORTHsystem uses it.
How FORTH Uses the Disk
Nearly all FORTH systems use disk memory.
Even though
memory is not absolutely
necessary
for a FORTH system,
difficult
to imagine FORTHwithout it.
disk
it’ s
To understand
what
disk memory does,
compare it with computer memory (RAM).
The difference
is
analogous to the difference
between
a
filing
cabinet
and a
rolling card-index.
So far you’ve
been
using computer
memory, which is like the
card index.
The computer can access this
memory almost instantaneously,
so programs that are stored
in RAM can run very
fast.
Unfortunately,
this kind of memory is
li mited
and relatively expensive.
On the other hand, the disk is called
a “bulk memory” device
because, like a filing cabinet,
it can store a lot of information
at a much cheaper price per unit of information
than the memory
inside the computer.
Both kinds of memory can be written
to and read from.
The compiler
compiles
all dictionary
entries
into computer
memory so that the definitions
will be quickly accessible.
The
60
Starting
perfect
is what
from the
you can
off the
FORTH
place to store source text, however, is on the disk, which
FORTH does.
You can either
send source
text directly
keyboard
to the interpreter
(as you have been doing), or
save your source text on the disk and then later
read it
disk and send it to the text interpreter.
SOURCE TEXT
DICT-
IONARY
(COMPUTE
I\
MEMOR'{)
DISK
MEMORY
Disk memory is divided
into units
called
“blocks.”
Many professional
FORTH development
systems have 500
blocks
available
(250 from each disk drive).
Each
block holds 1,024 characters
of source text.
The 1,024
characters
are divided
for display
into 16 lines of 64
characters
each, to fit conveniently
on your terminal
screen.
180
LIST
0
1
2
3
4
5
6
7
8
9 f
10
11
12
13
14
15
LARGE LETTER-F>
STAR
42 EMIT ;
STARS
0 DO STAR LOOP;
MARGIN
CR 30 SPACES;
BLIP
MARGIN STAR;
BAR
MARGIN 5 STARS;
f
BAR BLIP BAR BLIP BLIP
CR
61
3 THE EDITOR (AND STAFF)
This is what a block looks like when it’s
To list a block for yourself,
simply type
word !LISTI, as in:
listed
on your terminal.
the block-number
and the
180 LIST
To give you a better
idea of how the disk is used, we’ll assume
that your block 180 contains
the sample definitions
shown above.
Except for line 0, everything
should look familiar:
these are the
definitions
you used to print a large letter
“F” at your terminal.
Now if you were to type:
180 LOAD
you would send block 180 to the input stream and then on to the
text interpreter.
The text interpreter
does not care where his
text comes from.
Recognizing
the colons,
he will have all the
definitions
compiled.
Notice that we’ve put our new word F on line 9. We’ve done this
to show that when you load a block, you execute
its contents.
Simply by typing:
180 LOAD
all the definitions
will
printed
at your terminal.
be compiled
and
a letter
“F”
will
be
Now for the unfinished
business:
line
0.
The
words
inside
the parentheses are for humans only;
they are neither
compiled
nor executed.
The word [1j
(left parenthesis)
tells
the
text
interpreter
to skip
all the following
text up
to the terminating
r~ht
parenthesis.
Because W is
a word, it must be set off
with a space. t
It’s good programming
blocks with comments,
them.
tFor
practice
to identify
your application
so that fellow programmers
will understand
Beginners
The closing
parenthesis
is not a word, it is simply a character
that is looked
for by [1), called
a delimiter.
(Recall
that the
delimiter
for [:] is the closing quote mark.)
62
Starting
Here are a few additional
ways to make your blocks
1.
Separate
the
three spaces.
2.
Break definitions
spaces.
up into
3.
If the definition
but the first line.
takes
4.
Don’t put more than
unless
the definitions
related.
To summarize,
the
concern disk blocks
name from the
three
are:
contents
phrases,
separated
one line,
commands
we’ve
learned
(n
Lists
LOAD
(n
Loads a disk block
(compiles or executes).
—
)
by
by double
indent
all
definition
on a single
line
are very short
and logically
LIST
( XXX)
to read:
of a definition
more than
one
easy
FORTH
a disk block.
Causes the string xxx
to be ignored by the text
interpreter.
The character
is the delimiter .
so far
that
63
3 THE EDITOR (AND STAFF)
Dear EDITORt
Now you’re
ready
First
an empty blockt
find
to learn
how to put your text
and list
it,
using
on the disk.
the form:
180 LIST
When you list an empty block, you ’11 see sixteen
line numbers (0 1~ running
down the side of the screen,
but nothing
on any of
the lines.
The “ok” on the last line is the signal
that the text
interpreter
has obeyed your command to list the block.
By listing
a block,
going to work on.
you also
select
that
block
as the
one you’re
180
‘{OUAREHE\\E
:
180
……
.——-··-·-·-··.
–
——·· ·· ·–
CURI\ENT
BLOCK.
/80
A “pointer”
The terminal
memory
Now that you’ve made a block
typing the word
“current,”
in computer
(RAM).
you can list
it by simply
L
Unlike ILISTI, [!!I does not want to be preceded
instead,
it lists the current
block.
tFor
Those Whose EDITOR Doesn’t
The FORTH-79 Standard
does
system
may use a different
documentation.
tFor
People
Follow
These
not specify
editor:
if
by a block
number;
Rules
editor
commands.
Your
so, check
your system
at Terminals
If you’re using someone else’s
system, ask them which blocks ate
available.
If you’re using your own system, try 180. It should be
free (empty).
Starting
64
FORTH
L
YOUAREHERE:
110
/80
Now that you have a current block, it’s time to select
a current
line by using the word [‘.fl. Suppose we want to write something on
line 3. Type:
3T~====~
t
“””
[!] lets you select
the current line.t
It also performs a carriage
nothing).
return, then ~ the given line (which so far contains
At the end of the line, it reminds you which line you’re on:
3 T
A
3
ok
(Remember, we’re underlining
the computer’s output for the sake of
clarity.)
The caret at the beginning
of the line is the EDITOR’s
cursor, which points to your current character
position.
On your
f
terminal the caret might look like this:
tFor
the Curious
Actually,
pointer.
the cursor position,
not the line
More on this in a future footnote.
number, serves
as the
3 THE EDITOR (AND STAFF)
Now that your sights
current line by using
are
~-
65
fixed,
you can
put
some text
in the
P HERE IT ISmI!Jlm ok
[RIputs the string
that follows it (up to the carriage
return)
on
It does not type out the line.
If you don’t
is really
there, you can type:
the current
line.
believe
the string
3 T
or simply:
L
toj
a
HI
IT
4
,a
5
6
r
,
8
,0
II
IL
,.
/5
,,
Remember that
were
01(
your current
position
remains
the
same,
so if you
to now type
P THERE IT WENTCiilml3 ok
followed by [!;],you’d
former on line 3.
see that
the
latter
string
had replaced
the
[RIfollowed by at least two blank spaces (one
Similarly,
entering
the other as the string itself)
to separate
the [RIfrom the string,
causes
the former string
to be replaced
by a blank space;
in
other words, it blanks the line.
In this chapter
the symbol
So to blank a line, type:
11
11
)15
means that
you type
a blank
space.
Starting
66
Character
Editing
In this section,
within a line.
FORTH
Commands
we’ll
show you how to insert
and delete
text
Before
you can insert
or delete
text,
you must be able
position
the EDITOR’s cursor
to the point
of insertion
deletion.
Suppose line 3 now contains:
to
or
IF MUSIC BE THE FOO OF LOVE
and you want to insert the second “O” in “FOOD,” you must first
position
the cursor after the “FO” like this:
IF MUSIC BE THE FOADOF LOVE
To position
as in
the cursor,
use the command
00, followed
by a string,
F FOC!ll!ImJ
00searches
forward from the current position
of the cursor until
it finds the given string
(in this case “FO”), then places
the
cursor right after it.
t°AIF MUSIC BE THE FOO OF LOVE
~
~A
IF MUSIC BE THE FOO OF LOVE
IF MUSIC BE THE F;ffjOF
LOVE
If you don’t know the starting
position
of the cursor, first type
“3 T” to reset the cursor to the start of the line.
00 then types
the line, showing where the cursor is:
IF MUSIC BE THE FOAD OF LOVE
3 ok
3 THE EDITOR (AND STAFF)
67
Nowthat the cursor is positioned where you want it, simply enter:
I
ocmmm
and CT]will insert
the character
“O” just behind
the cursor.
IF MUSIC BE
CT]then types
the corrected
line,
including
the cursor:
IF MUSIC BE THE FOOAD OF LOVE
3 ok
To erase a string (using the command ~), you must first
string,
using I!]. For example,
if you want to erase
“MUSIC,” first reset the cursor with:
3
find the
the word
Tm;::mm
then type:
F MUSicm;::mm
IF MUSICABE THE FOOD OF LOVE
3 ok
and then simply:
~
erases
the string
FOODOF LOVE
IF
~ then
you just found with~-
types
the line,
including
the cursor:
IF A BE THE FOOD OF LOVE
The cursor
word:
is now in a position
3 ok
where
you can
insert
another
68
Starting
IF
FORTH
3 ok
ROCKA BE THE FOOD OF LOVE
The command ~ finds
and deletes
a string.
you two commands for
of [Kl and I!], giving
if your cursor is here:
example,
It
the
is a combination
price
of one.
For
IF ROCKA BE THE FOOD OF LOVE
then
you can delete
“FOOD” by simply
typing:
D FOODClIJ!Ilm
IF ROCK BE THE A OF LOVE
Once again,
you can
insert
text
3 ok
at the
new cursor
position:
I CHEESEBURGERSClIJ!Ilm
IF ROCK BE THE CHEESEBURGERSA OF LOVE
Using @I is a little
more
With the two-step
method,
erase before
you erase it.
dangerous
you know
than
exactly
3 ok
using
what
The command [Bl replaces
a string
that
you’ve
is a combination
of 00]and [!]. For instance:
[El and
you’re
already
F NEED AClIJ!Ilm
COMPUTERS NEED AA TERMINAL
R CAN BEClIJ!Ilm
COMPUTERS CAN BEA TERMINAL
ffil is
certain
great
when you want
string.
For example,
( SAMPLE DEFINITIONS)
then it’s
not easy to ~ your
the cursor
over to the space
the following
method:
F MPTYClIJ!Ilm
then
R EMPTYClIJ!Ilm
rn).
then
going
to
found.
It
2 ok
2 ok
to make an insertion
in
if your line O is missing
MPTY
front
of
an “E”:
a
0 ok
way through
all those spaces to
before
MPTY. Better
you should
get
use
3 THE EDITOR (AND STAFF)
ITILLIis
everything
the given
69
the most powerful
command for deletion.
It deletes
from the current
cursor position
up till and including
string.
For example, if you have the line:
BREVITY IS THE SOUL”, THE ESSENCE, AND THE VERY SPARK OF WIT.
(note
the cursor
position),
then
the phrase:
TILL SPARKmI!lmJ
or even just
TILL KCIII!Jlm
(since
there’s
only
one “K”) will
produce
BREVITY IS THE SOUL “OF WIT
Has a nicer
ring,
doesn’t
and the
5 ok
it?
The Find
Buffer
Insert
In order
understand
buffer.”
to use the EDITOR effectively,
the workings
of its “find
You may not have known it,
Buffer
you really
have to
buffer”
and its “insert
but when you typed
F MUSICCIII!Jlm
the first
something
parlance,
is located
thing
[fl did was to move
called
the “find
buffer.”
is a temporary
storage
place
in computer memory (RAM).
the
string
“MUSIC” into
A buffer,
in computer
for data.
The find buffer
Starting
70
FORTH
YOU AREHERE:
F h\USIC
C.UR1’ENT
BLOC.I
6 /
+;
Sometimes you don’t want to get rid of your whole application,
only part of it.
Suppose you were to write a word processing
application
(so you can enter text, edit it in memory, then output
it to a printer).
After you’ve finished
the basic
application,
you want to add variations,
so it can use one format
for
correspondence,
another
format
for magazine
articles,
and
another
format for address
labels.
DICTIONAlW
SYSTEM
DEFINITIONS
WOP.I)
PROCESSING
APPLICATION
LABEL
FDRM~T
tFor
People
on a Multiprogrammed
IEMPTY! “forgets”
not anyone else’s.
your
own personal
System
extension
of the
dictionary,
3 THE EDITOR (ANDSTAFF)
81
In FORTH these three variations
are called
“overlays”
because
they are mutually exclusive
and can be made to replace
each
other.
Here’s how.
The basic word processing
application
should begin
The last definition
should be a name only, such as
with !EMPTY!.
: VARIATIONS
This is called
a “null definition”
because it does
mark a place in your portion of the dictionary.
nothing
but
Then at the
expression
include
the
beginning
FORGETVARIATIONS
of each
variation
block,
VARIATIONS;
Now when you load one variation,
it
!FORGET!s back to the null definition,
compiles
a new null definition,
and
then
compiles
the
variation’s
definitions.
When you load the other
variation,
you replace the first overlay
with the second overlay.
One more trick:
what if the source text for your application
takes more than one block?
The best solution is to let one block
load the other blocks.
For example, your “load block” might
contain:
0 ( MY APPLIC HION>
1
2 180 LOAD
–
182 LOAD
—
It’s much better to let a single load block !LOAD)all the related
blocks than to let each block load the next one 1n a chain.
Now you know the ropes of disk storage.
You’11 probably want to
edit most of the remaining
examples and problems in this book
into disk blocks rather
than straight
from the keyboard to the
interpreter,
especially
the longer ones.
It’s just easier that
way.
Starting
82
A Handy Hint –
FORTH
When a Block Won’t [IiOA5I
On some FORTH systems,
the following
scenario
may sometimes
happen to you: you load some new definitions
from a block, but
when you try to execute
them, FORTH doesn’t
seem to have ever
heard of them (responding with a “?”).
First y…
Top-quality papers guaranteed
100% original papers
We sell only unique pieces of writing completed according to your demands.
Confidential service
We use security encryption to keep your personal data protected.
Money-back guarantee
We can give your money back if something goes wrong with your order.
Enjoy the free features we offer to everyone
-
Title page
Get a free title page formatted according to the specifics of your particular style.
-
Custom formatting
Request us to use APA, MLA, Harvard, Chicago, or any other style for your essay.
-
Bibliography page
Don’t pay extra for a list of references that perfectly fits your academic needs.
-
24/7 support assistance
Ask us a question anytime you need to—we don’t charge extra for supporting you!
Calculate how much your essay costs
What we are popular for
- English 101
- History
- Business Studies
- Management
- Literature
- Composition
- Psychology
- Philosophy
- Marketing
- Economics