Lab 1: Forth Basics


Remember:

Solutions to this lab

Running Forth

The version of Forth we'll use is GForth 0.4.0 - the executable is called gforth, and it's in a directory called: /package/jpower/se209/bin     So put this in your path, and you're ready to go...

For example, if you're using the c-shell you might type:

You should then see: Before you start the exercises below, try some simple maths! Remember that typing a number causes it to be pushed onto the stack; typing an operator (like +,-,*,/ or MOD) causes it to be applied to the topmost two elements in the stack. Type in some of the other commands (from the lecture notes) just to make sure you have the hang of them...

Remember: To print the stack, just type .S

Some simple words

Define Forth words to perform the following:
  1. max3 ( n1 n2 n3 -- n )
    Gets the maximum of the topmost three stack elements.

  2. is-even ( n -- flag )
    True if the number on top is even, false otherwise (use MOD with 2).

  3. mk-odd ( n -- n )
    Rounds number on top of stack up to the nearest odd number (i.e. add 1 if the number is even, otherwise do nothing).

  4. quadratic ( n1 n2 n3 n4 -- n )
    Works out the formula ax2 + bx + c, assuming that the four numbers on top of the stack represent a, b, c and x (with x topmost).

    Words with loops

    Define Forth words to perfom the following:


    NUIM Logo James Power,
    Dept. of Computer Science
    Last revised: 15 February 2000