TEACH VEDPOP                                 Revised A.Sloman Sept 96

This teach file reviews the procedure for switching between TEACH, VED
and Pop-11 that was introduced in TEACH VED. It shows you how to define
very simple programs, which Pop-11 can compile, and then run for you.

It does not attempt to define the language Pop-11 so much as to
introduce you to the interaction between Pop-11 and the editor, so that
you can then go on to work on exercises that teach you the language in
more detail. (Read the Pop-11 Primer for a more comprehensive overview
of the language.)

In particular this "teach file" makes use of the fact that VED knows how
to communicate with the Pop-11 compiler. It shows how you can prepare
Pop-11 programs in VED then ask VED to give them to the compiler, to
translate them into machine code ready for use. It also shows how you
can ask VED to ask Pop-11 to obey commands, e.g. to run your program.

You'll see how you can use VED for testing a program by varying the
commands you give it.

You will see how, when the program produces any printed output, the
output appears in a new VED buffer. This output can be deleted if you no
longer need it, or it can be saved in a file, e.g. for inclusion in a
project repor, or added to an email message in which you ask for help
when you cannot work out what is wrong with your program.

Later (in TEACH VEDPROC) you will learn how to prepare a whole program
in a file by itself. For now this file will introduce only fragments of
programs, for illustrative purposes.

Here is a table of contents for this file. Use the "ENTER g" command to
Go to desired section, if you are revising. Otherwise, simply skip to
the end of the table, and read on.


CONTENTS
========

 -- WHY DO THIS?
 -- PRESUPPOSITIONS
 -- Running Pop-11 commands
 -- Types of load (compile) commands available in VED
 -- Compiling just one line: examples
 -- What the print-arrow "=>" does
 -- More on Pop-11
 -- Pop-11 has a "syntax" or "grammar"
 -- -- Basic symbols: characters
 -- -- More complex symbols, denoting: numbers words, and strings
 -- -- Some Pop-11 words composed of special symbols
 -- -- User-declared symbols
 -- -- -- Initialised declarations
 -- -- -- Declaring several variables at once
 -- -- -- Initialising several variables at once
 -- -- Command terminators ";" and "=>" and "==>"
 -- -- Complex expressions in Pop-11
 -- Spaces in Pop-11
 -- When you have finished reading this file

-- WHY DO THIS? -------------------------------------------------------

Taking a course in AI programming involves learning how to specify,
design, implement, test, debug and document a complex behaving system,
whether it is a system that models some aspect of human competence, or
tests a theory about what certain algorithms can do, or serves a useful
purpose.

For an important class of systems the ONLY way to do this (at present)
is to use a textual programming language. What alternatives are there?

1. For relatively simple sub-tasks there are graphical programming tools
whereby you assemble a program by selecting components with a mouse: but
it is hard to give such tools the same generality as a text-based
programming language. In any case the pre-existing libraries will have
to be produced using a text-based language, and if the libraries
you need do not exist you will have to program them.

2. For other cases you can design a neural net and give it examples of
inputs and outputs, letting it learn how to generalise from those
examples (or interpolate between them), or you can design an
evolutionary algorithm and let it "evolve" a solution to a problem
through large numbers of trial and error experiments.

But there are many design tasks which (at present, and perhaps forever)
are far beyond the capabilities of these techniques. For example: giving
examples of AI programs and examples of their behaviour to a neural net
would not in general enable the net to design new programs by
generalising from those examples. (Why not? The answer is not obvious.)

So, for the foreseeable future it will be necessary to specify
explicitly in a textual language the structures and procedures required
for many complex designs, though graphical tools may be useful for
combining previously constructed libraries.

However, the task of creating a textual specification is a hard
intellectual challenge: lots of information is required (about available
programming constructs and libraries) and it is typically very difficult
to get the design right first time. Moreover, when something is wrong it
can be very hard to find out exactly what has gone wrong. So you need to
learn to use not only a language with the power to support the
mechanisms you want to design, but also a development environment that
helps you. Good tools make a huge difference, in programming as in any
other process of construction.

The Poplog system, including its editor VED, is one such environment.
But because its functions are quite complex, learning to use it is not
trivial: don't expect it to be as easy as learning to use a word
processor. Moreover, some of the earlier bits may seem rather boring.

However later you will appreciate their power.


-- PRESUPPOSITIONS ----------------------------------------------------

This teach file assumes that you already know:

(a) How to move around a VED file (See TEACH TEACH and TEACH VED),
    using either the mouse pointer or keyboard "move" keys,

(b) How to create your own VED file and save it on the disk and
    edit it again when you next log in (TEACH VED)

(c) How to switch between files (see TEACH SWITCHWINDOW, TEACH BUFFERS,
    the latter shows how to get an index of current buffers using ESC E)

(d) How to mark a range of text in the file (TEACH MARK)

(e) How to use LMR to load (compile) a marked range (TEACH LMR)

This file will provide revision of point (e) and introduce more examples
of interaction between VED and Pop-11 including a graphical example
at the end.

You may also find the Birmingham Poplog menu facility useful if it is
available on your system. If you do not see the Toplevel column of
Poplog menu buttons try typing

    ENTER menu

If that works you will have a column of buttons including one labelled
"Compiling..." If you click on that option with the left mouse button,
you will get a new menu giving options. Or you can bring up that menu
directly with the "ENTER menu compiling" VED command.

If you have a VED keyboard map, please consult it, to see which
function keys on your keyboard provide those facilities.


-- Running Pop-11 commands --------------------------------------------

At the moment, you are reading a TEACH file using the VED editor. The
main commands you will have learnt so far involve commands for inserting
or deleting text, for moving the VED cursor, for startup up a new file,
for quitting a file, and so on.

The Pop-11 programming language enables you get the computer to do many
more things, including doing numerical calculations, manipulating lists
of words and other things, creating plans, interpreting sentences,
analysing images, and solving problems. When you have learnt the
language you can give commands directly to the Pop-11 compiler. However
it is most convenient to ask the editor to do this for you. The editor
saves your commands so that you can repeat them or modify them and then
repeat. The rest of this file teaches you how to do that.

Further, because the editor itself is just a program written in Pop-11
you can later learn how to program it with additional procedures to
provide additional support for your programming tasks, if you wish.

For now, you will learn to do the following:

(a) Prepare your Pop-11 procedure definitions and commands:
    i.e. editing

(b) Hand the Pop-11 text to the compiler for translation to machine
    code and execution: i.e. loading, or compiling

(c) Examining and analysing any output produced by your programs or
    the compiler.

We describe (b) as loading or compiling your Pop-11 instructions. The
words "load" and "compile" are used interchangeably, for historical
reasons, though strictly "compile" is more accurate, or
"compile_and_run".

Any printed output resulting should appear in another VED buffer called
'output.p'. This is just another VED file, and you can manipulate the
text in that file just like any other file. You will find that the
file grows steadily during development and testing. You can use a marked
range and the "ENTER d" command to delete unwanted output from the file.

Here is a simple example: put the VED cursor on the following line and
then press the ESC key followed by the D key.

    pr('Hello there - how are you?\n');

Notice how a new file called 'output.p' appears with some text in it. If
your screen does not have enough space for this window and the output.p
window you can use the window manager to reduce the number of lines in
the window (it is best not to reduce the number of columns). Put the VED
cursor back on that line and do ESC D again a few times.

That instruction asks Pop-11 to create a STRING containing some text
followed by a newline character, and give the string to the "pr"
command, to print it. VED gives the whole instruction to Pop-11, which
obeys the command.

You can go back and change the text between the two string quotes '  '
without deleting the quotes, and then re-do the command using ESC D.

Each time you ask VED to give the command, Pop-11 compiles and runs it,
producing some text as ouput, which VED puts in the output.p file.

Using ESC D to load one line is just one of several ways of telling
VED to give Pop-11 commands to the Pop-11 compiler. Some are described
in the next section.


-- Types of load (compile) commands available in VED ------------------

The commands available in VED to hand Pop-11 instructions to the
compiler are of different sorts. They can be concerned with the whole
file, with a marked range, with a procedure definition (explained below)
or with only a single line of Pop-11. For each case you can give a
command using either one of the Buttons on the Compiling... menu,
or by giving an ENTER command, or by using a keyboard sequence, as
follows.


    Compiling...menu button         ENTER command      Keyboard
    (and explanation)
    ===========================================================

    CompileRange                    ENTER lmr           CTRL-d
    Load (compile) a marked range

    CompileFile                     ENTER l1          -------
    Load (compile) the whole file

    CompileProc                     ENTER lcp           ESC c
    Load (compile) the "current" procedure

    CompileLine                     ENTER ltl           ESC d
    Load (compile) this line

Note 1.
The first command (load marked range) is the most basic and general
function. It can always be used instead of any of the others, since you
can mark the whole file, or a part of a file, or even just one line,
and then load the range.

However, it is convenient to have abbreviations for the most commonly
used special cases, which make it unnecessary for you to mark the
relevant bit of the file.


Note 2.
There is no keyboard shortcut for ENTER l1, though if you wish you
can later learn how to define one: VED is programmable in Pop-11.


-- Compiling just one line: examples ----------------------------------

Try the "load this line" command on the following examples, using each
of the options (CompileLine button, ENTER ltl, and ESC d, or a LOADLINE
function key if your keyboard map shows one). Note what is printed out
in your output.p file in each case, and try varying the commands, e.g.
by changing the numbers:

    3 + 5 =>

    sqrt(16) =>

    30/10 =>

    30/20 =>

    99*9 =>

Note that in Pop-11 "*" means multiply two numbers. So the last command
means multiply 99 by 9 and print out the result. Also the division
operator "/" sometimes produces a "ratio" when the denominator does
not exactly divide the numerator, e.g. dividing 3 by 2 gives: a
ratio which Pop-11 prints out as: 3_/2

In each case the result of the calculation is printed in the file called
'output.p'. Here is another Pop-11 command, to reverse a list of words
and print out the reversed list:

    rev([mat funny the on sat cat the]) =>

Try modifying that command and re-compiling it to see what happens. E.g.
you can change the words, or insert some numbers. Try loading the line
in different ways. (I prefer using ESC d, but you may find it easier
to remember another way of doing it.)

We now explain in more detail what is going on in the above commands.


-- What the print-arrow "=>" does -------------------------------------

Each of the preceding commands contained two parts:

1.  The first part, before the "=>" calculates or creates something,
    such as a number or a list, which is left in a region of memory
    called "the user stack", a feature of Pop-11 (and the programming
    language Forth).

2.  The second part of the command is the print arrow "=>" made by
    typing the "=" key followed by the ">" key. This tells Pop-11 to
    print out all results left on the stack. (Sometimes more than one
    result is left there.)

The combined command causes something to be printed in the output.p
file, preceded by two asterisks, thus: "**".

Sometimes later on you will need to use the "pretty" print arrow "==>"
to cause long lists of lists to be printed neatly.


Try the following slightly more complex calculation (Load This Line):

    (9 + 9) * 99 =>

This should print the following in your output.p file

    ** 1782

Note: the spaces between numbers and symbols are optional. Use them when
you think it makes your code easier to understand. Try all these, and in
each case try to anticipate what will be printed out.

    sqrt(16) =>

The arithmetic operator "**" means raise to the power of. Try
these, and variants:

    10**2 =>

    10 ** 3 =>

    3 ** 10 =>

    3 ** 300 =>

Now type in a command to multiply 12 by 12 and print out the result.

Type in a command to raise 4 to the power 5 and print out the result.
The result should be 1024.

Type in a command to add 3 and 5 and multiply the result by 16. You will
need to use parentheses "(" ")" to group the numbers to be added. The
result printed out should be 128.

-- More on Pop-11 -----------------------------------------------------

Those were some very simple commands in Pop-11. The language is very
much richer than these commands suggest, and it will take some time to
get used to the variety of things you can do in Pop-11, including the
use of lists (and lists of lists, and lists of lists of lists) to store
and manipulate information about some domain.

The purpose of the rest of this teach file is not so much to teach you
Pop-11 as to give you some fluency in manipulating the editor with
Pop-11 examples.

This fluency is ESSENTIAL if you are to learn to develop, test and debug
Pop-11 programs easily. It is also essential for learning to read and
make good use of online teaching materials and demonstration libraries.

The examples given below will indicate a tiny subset of the things you
can do in Pop-11. Additional teach files will introduce more and more of
the language, and pay less attention to the editor.

There is a brief summary of Pop-11 in TEACH POPCORE. (A printed version
will be made available later.)

More complete information about the language is available in the Pop-11
Primer. Here is a simple introduction to a subset of Pop-11, to provide
a context for the examples that follow.


-- Pop-11 has a "syntax" or "grammar" ---------------------------------

-- -- Basic symbols: characters

Like all languages, Pop-11 has some basic symbols that can be used to
form words and other objects. The basic symbols, usually referred to
as "characters" include all the printable characters that you can
type on the keyboard, including the "space" and a "newline".

-- -- More complex symbols, denoting: numbers words, and strings

The basic symbols can be combined to form

    Numbers:    e.g. 1,  66, 77.432
    Words:      e.g. cat, define, vars, elseif, enddefine, +, =>
    Strings:    e.g. 'cat'  'string with spaces'  '**tt##aa**'

and other objects. In fact Pop-11 has a rich collection of "datatypes"
but for a while only words, strings, numbers and lists should suffice
for your programming exercises.

-- -- Some Pop-11 words composed of special symbols

Some of the words in Pop-11 are special symbols like these (some of them
words containing a single character):

    Arithmetic operators:       +  *  /  **  (and others)
    List brackets               [    ]
    Semi-colon                  ;
    Comma                       ,
    Assignment arrow            ->
    Equals sign                 =
    Print arrow                 =>
    "Prettyprint arrow"         ==>     (used to print lists of lists)
    Others                      ?  ??  ^  ^^  -->  <>  (and others)

Later you will learn to use all these symbols, and more!

-- -- User-declared symbols

Besides the built in symbols in Pop-11 a Pop-11 program can include
symbols that you have constructed out of the basic characters. For
example if you define a procedure to do something you will need to give
that procedure a name, so that you can later tell Pop-11 to run it
whenever you need to. Later you will see how to do that using
the "define .... enddefine" construct.

Also sometimes you will declare "variables" i.e. names that will refer
to something that you type in or which a program creates, but which
might refer to different things at different times. For example here is
a declaration of a variable "bignumber". Load this line.

    vars bignumber;

And here is how you give it a value, using the assignment operator: load
this line

    999999999 -> bignumber;

And here you can give it an even bigger number, twice the size: load
this line

    bignumber * 2 -> bignumber;

Now print out the value of the variable bignumber:

    bignumber =>

See what happens if you repeat the last TWO commands a few times.

Note that in Pop-11 "assignment" of a variable normally goes from left
to right, unlike many other languages. In Pop-11 you first specify or
calculate a value, then assign it to a variable. In many other languages
you specify a variable tha tis to receive a value, then say which value
it should get.

Exercise:
Type in an expression to assign the number 55 to the variable bignumber,
then print out the value.

-- -- -- Initialised declarations

Instead of first declaring a variable then assigning to it, you
can do both at once, using the "=" sign within the declaration;

    vars smallnumber = 2;

Note that this "initialised declaration" is equivalent to two commands:
the variable declaration and the assignment, i.e.

    vars smallnumber;   2 -> smallnumber;

In an initialised declaration, the assignment goes from left to right,
which is very unusual in Pop-11 though common in other languages. Load
this declaration and then check the value of the variable:

    vars smallnumber = 2;

    smallnumber =>

You can use the value of an existing variable to initialise a new
variable, e.g. load these two lines:

    vars medium_number = smallnumber * 10;

    medium_number =>

Exercise:
Using the format

    vars <variable> = <initial value> ;

Type in a declaration of a variable called "colours" initialised to this
list of words:

    [red orange yellow green blue indigo violet]

(Don't forget the final semicolon). Compile your declaration and then
give a command to print out the value of the variable colours.

Declare a variable called total and initialise it with the result
of adding 1, 2, 3, 4, 5, i.e. (1 + 2 + 3 ....).


-- -- -- Declaring several variables at once

You will find it useful in Pop-11 to be able to declare and use some
"global variables", and also "local variables" used inside procedure
definitions. Variables are names that can be associated with values,
possibly changing values.

Here is how you declare three global variables with names "xx", "yy",
"zz".

    vars xx, yy, zz;

Unless you have already used these variables, their initial values will
be undefined. Use the Load This Line command on that declaration, then
on the following print commands, and look at what is printed out in your
output.p file.

    xx =>

    yy =>

    zz =>

You can assign a word to xx and then print out the value:

    "elephant" -> xx;

    xx =>

Load those lines, then change the word and redo the commands.


-- -- -- Initialising several variables at once

The next command will declare and initialise two variables list1 and
list2. However, as it goes over three lines you cannot use the "load
this line" facility. You will have to mark all three lines, then use
"load marked range". (Can you remember the different ways of doing that
listed above?)

    vars
        list1 = [the cat sat on the mat],
        list2 = [the flea sat on the cat];

Mark and load those three lines, and then load this line:

    [ ^^list1  and  ^^list2 ] =>

Notes:
    o If you use two or more initialisations, THERE MUST BE A COMMA
      BETWEEN THEM.

    o The declarations introduced by "vars" can go over several lines.

    o The set of declarations MUST END WITH A SEMICOLON ";".


-- -- Command terminators ";" and "=>" and "==>"

Pop-11 commands can run over several lines. So some indication is needed
of when a command ends. In Pop-11 this is done with a special
expression "separator", i.e. the semicolon.

For example here is a command to calculate 66 times 9 and print out the
result. Compile this line:

    pr(66 * 9) ;

You could also make it take three lines. Mark and load this:

    pr(
    66 *
    9) ;

For convenience, Pop-11 allows you to leave out the semi-colon after the
print arrows:

    666 * 9 =>

    6666 * 9 ==>

(Later you will learn that the semicolon can also be omitted just before
a closing bracket.)


-- -- Complex expressions in Pop-11

The Pop-11 text items, i.e. words, strings and numbers, can be combined
to form more complex expressions of several kinds.

    Declarations tell Pop-11 that you are declaring a new variable
        or procedure name.

    Initialised declarations include a declaration and an assignment

    Imperatives tell Pop-11 to do something, e.g. print something,
        store something in the Pop-11 database, read something from
        a file.

    Denoting expressions can be used to refer to a Pop-11 object, either
    by creating it or by indicating where it exists if it already does.

    For example if we use an initialised declaration like this:

        vars list = [the cat sat on the mat];

    Then we could have imperatives like this, to make a double
    length version of the list and print it out

        [ ^^list  ^^list ] =>

    Try it.


Exercise: how many denoting expressions does the following contain:

    3 + 4 + 5 =>

Hint: there are more than four, including these:
    3
    4
    4 + 5

Later you will learn how to combine declarations, imperatives and
denoting expressions in defining procedures to do new things.


-- Spaces in Pop-11 ---------------------------------------------------

Try entering some more arithmetic expressions, eg:

     12-3+5=>

You can put spaces between items in the expression. An item is a single
number (eg 12) or a symbol (eg + or => ) You could write
the expression above as

     12 - 3 + 5 =>

but Pop-11 will not interpret the expression correctly if you split
up the individual text items. I.e. the following will not work. Try
loading them:

    1 2 - 3 + 5 =>

    12 - 3 + 5 = >

Which of these are valid Pop-11 expressions:

    2 3  + 4 5 =>

    3-5+45=>

    34     +      10       =>

    1 + 3 - 5 = >


If you are not sure, then try compiling them and see what happens.
The examples that are not valid expressions in Pop-11 will produce
"MISHAP" messages. You will need to learn how to use these messages
to help you find things that are wrong with your programs.

Some mishap messages come on VED's command line, some in the output.p
file. You'll later learn the difference between "compile time" errors
and "run time" errors.


Exercise:
    What are the differences between declarations, imperatives, and
    expressions?

    Is this legal Pop-11:       1 3 5 =>

    Is this:                    [1 3 5] =>

(try loading them).


-- When you have finished reading this file ---------------------------

Now move to TEACH VEDPROC to learn how to create a file containing
procedures and test commands.


--- $poplocal/local/teach/vedpop
--- Copyright University of Birmingham 1996. All rights reserved. ------
