Kajo Lab 101

Write your first Forth word.

Give two stack operations a name. Step through your new word, then try it in Kajo Lab with a saved recording and no Pico connected.

Give the operations a name.

Forth calls each named operation a word. This definition makes a word called double.

: double ( n -- 2n ) DUP + ;

The colon starts the definition. DUP copies the number at the top of the stack, then + adds the top two numbers. The semicolon completes the definition.

( n -- 2n ) is a comment. It describes the stack effect, which is what the word takes from the stack and what it leaves behind. double takes one number and leaves twice that number.

Follow the data stack.

Start with one number on the stack, then apply DUP and +. The top value is on the right. Try 7 first, then predict the result for 9 before you step.

Read the worked example with 7
  1. Start with 7[7]One value is on the stack.
  2. Run DUP[7 7]The first 7 stays. A copy goes on top.
  3. Run +[14]The two top values are replaced with their sum.
Check your prediction for 9

Starting with [9], DUP leaves [9 9] and + leaves [18].

The browser exercise shows the two operations inside double. Lab also shows the instructions for entering and returning from the word.

Run the word in Kajo Lab.

On Windows, use the recording to give Lab an observation to inspect. Lab calls on-sample for that observation. This draft uses the fixed number 7, so the sensor value does not affect the exercise.

  1. In Lab, choose Open recording or session… and open the downloaded Night Light recording.
  2. Open Program, choose Forth and replace the text in Experimental Forth with both lines below.
: double ( n -- 2n ) DUP + ;
: on-sample 7 double ;
  1. Set the observation number to 1 and choose Inspect observation.
  2. In Stacks, watch the Data stack as you choose Next frame. It starts empty, then holds 7 while the call enters double. After + it holds [14].
  3. Step through both returns until you see This callback: result 14. The saved observation still shows Recorded callback: result 1.

Write a word that triples its input.

First, change 7 to 9 in on-sample, choose Inspect observation again and step through the result. Now write triple with two DUPs and two +s. Give it the stack effect ( n -- 3n ) and call it from on-sample with 7. Can you predict what the stack holds just before the last +?

Show the triple solution
: triple ( n -- 3n ) DUP DUP + + ;
: on-sample 7 triple ;

Replace the Experimental Forth draft with these two lines and choose Inspect observation again. After the second DUP the stack holds [7 7 7]. The first + leaves [7 14]. The final + leaves [21]. Step through both returns to see This callback: result 21.

Study references.