8th Tutorial

Lession 9: Conditionals and loops

Note: if you haven’t yet installed 8th, please do so right now and follow the installation instructions as presented in the manual!

Conditionals

A “conditional” is a way of determining which of two (or more) paths to take. For example, if it’s the afternoon I may want to say “good afternoon”, while if it’s the morning I may want to say “good morning”. In 8th, the primary conditional words are if, else and then, and are used like so:

: am-or-pm \ hour -- msg 12 n:< if "good morning" else "good afternoon" then ;
This new word “am-or-pm” looks at a number on TOS and if it is less than 12, returns the string “good morning”; otherwise, it returns “good afternoon”. A more complete example might look like this:
: greeting \ hour -- msg dup 12 n:< if drop "good morning" else 18 n:< if "good afternoon" else "good night" then then ;
In this case you see that you can put a conditional inside a conditional. You should also note that you do not have to have an “else” phrase, but you must have a matching “then” for the opening “if”. Because you need to do two comparisons of the number with “if”, you need to use “dup” and remember to “drop” in the appropriate place.

Using an alternative “conditional” called caseof makes this code easier to maintain and understand:

["good morning", "good morning", "good afternoon", "good evening"] var, greetings : greeting \ hour -- msg 6 n:/ 3 n:min greetings @ swap caseof ;
Here we got rid of the “if...then” by converting the conditional to a “table-lookup”. It is easier to maintain and understand, particularly if there are a lot of cases to be examined.

Loops

There are a few types of looping constructs in 8th:

  • repeat… again — this is an “infinite loop”
  • repeat… while — repeats as long as TOS is true
  • loop and loop- — repeat a fixed number of times, counting up or down
  • times — repeat a fixed number of times
For example, to repeat a message five times you might do this:
( "Hello, world" . cr ) 5 times
You could also have done this:
( "Hello, world #" . . cr ) 1 5 loop
If you try the two samples, you’ll see what’s different between them. Try it now!

You can break out of a looping construct by invoking break inside the loop. It will break out at the end of the current iteration, not immediately as in C or Java.

Exercises

Try the following:

  • Using “loop”, print the numbers from 1 to 10, with spaces in between
  • Using “if… then” and “loop”, print the numbers from 1 to 10, and whether the number is even or odd (hint: use n:mod to determine the latter
  • Using “caseof”, print the names of the numbers from 1 to 10

Conclusion

You’ve been on a whirlwind tour of 8th’s basic functionality. Now it’s time for you to delve deeper into the manual as well as explore the wealth of sample code provided with 8th. Don’t forget to join the 8th forum where you’ll find help and answers to most of your questions. Enjoy 8th!