Conditionals II
Multilevel conditional words help your program make more than one decision. Here's an example:
: say-my-name dup 2 = -> "Two!" | dup 3 = -> "Three!" | 4 = -> "Four!" | otherwise "Whatever" |. . cr ;Take your time to understand
SAY-MY-NAME. Some pointers:
- The word pairs
->
and|
act likeIF ... THEN
pairs. - The final word is
|.
OTHERWISE
is the same astrue ->
Quiz
Question 1
Run
0 say-my-name 1 say-my-name 2 say-my-name 3 say-my-name 4 say-my-name 10000 2 + say-my-nameDo you understand how
SAY-MY-NAMEworks?
0 say-my-name \ Whatever 1 say-my-name \ Whatever 2 say-my-name \ Two 3 say-my-name \ Three 4 say-my-name \ Four 10000 2 + say-my-name \ Whatever, same as 10002 say-my-name
Question 2
Extend the programSAY-MY-NAMEso that it says the name of the number 43. Remember to check that your program works. What do all the
DUPs do?
: say-my-name dup 2 = -> "Two!" | dup 3 = -> "Three!" | dup 4 = -> "Four!" | 43 = -> "Forty-three!" | otherwise "Whatever" |. . cr ; 43 say-my-name \ Forty-threeSince
=consumes the number on the stack, we need
DUPto retain the number for furthur comparison.
Question 3
What would happen if we left out theOTHERWISEpart from
SAY-MY-NAME? What changes would you have to make to it so that it works perfectly? Test out your answer.
: say-my-name dup 2 = -> "Two!" . cr | dup 3 = -> "Three!" . cr | dup 4 = -> "Four!" . cr | 43 = -> "Forty-three!" . cr |. ;If we left out
OTHERWISE, nothing will happen when there is no match. We have to place
|.after the last comparison. Also,
. crhave to be between each
->...
|(or
|.) pair such that
. crwill only be executed when there is a match.