Conditionals I
Useful programs make decisions. Words to do this are known as conditionals.
The simplest conditionals are the pair IF ... THEN. An example:
: two? 2 = IF "Yes, this is two! :)" . cr THEN ;
We can test the word TWO?
3 two? ok 2 two? Yes, this is two! :) okUnderstand how this works:
- IF reads the top of the stack.
- If the item is
true
, then the stuff betweenIF
andTHEN
is executed. - If the item is
false
, then execution continues afterTHEN
.
ELSE
We can easily extend our program to include a dire warning if the value isn't 2:
: two? 2 = IF "Yes, this is two! :)" ELSE "No, this is not two. :(" THEN . cr ;Understand how this works:
- IF reads the top of the stack.
- If the item is
true
, then the stuff betweenIF
andELSE
is executed. - If the item is
false
, then the stuff betweenELSE
andTHEN
is executed. - Then execution continues after
THEN
.
Quiz
Question 1
Notice that I have slightly re-arranged the dot andCRafter
THEN. Why did I do this?
It is the same as following.
Re-arranging the dot and
Re-arranging the dot and
CRafter
THENcan avoid typing
. crtwice (after
IFand after
ELSE).
: two? 2 = IF "Yes, this is two! :)" . cr ELSE "No, this is not two. :(" . cr THEN ;
Question 2
Can you useIF,
ELSEand
THENin interpretation mode? Test out your answer.
No,
IF,
ELSEand
THENcan only be used in compilation mode, i.e., when defining words.
Question 3
Write a wordEVEN?which prints out "yay" if the value on the stack is even and "nay" if it is not. Make use of integer modulus,
MOD(see the Math section).
: even? 2 mod 0 = if "yay" else "nay" then . cr ; 4 even? \ yay 5 even? \ nay