
       ͻ
         Lesson 7 Part 180 F-PC 3.5 Tutorial by Jack Brown  
       ͼ

              Ŀ
                Recursive Greatest Common Divisor  
              

The greatest common divisor of two numbers a and b is the largest number
n that will divide into both a and b. Here is the recursive definition,
you figure out how it works
 
 :  GCD   ( a b -- n )   RECURSIVE
         CR ." Entering " .S
         DUP  IF   SWAP OVER MOD GCD
              ELSE DROP
              THEN
         CR ." Leaving " .S ;

              Ŀ
                Recursive Bubble Sort on the Stack.  
              

\ BUBBLE does one pass.  It is the recursive word!

 : BUBBLE  ( n n n ...  m m m ...  one pass )  RECURSIVE
         CR  ." ENTERING " .S
         DEPTH 1 >
         IF   2DUP  <  IF SWAP THEN
              >R   BUBBLE   R>
         THEN
         CR  ." LEAVING "  .S ;
 
 You can get rid of the entering and leaving .
 To use: put any numbers on the stack and type SORT
 
 : SORT ( n n n n ...    m m m m ... sorted )
         DEPTH 1 > IF
         DEPTH 1-  0 DO  BUBBLE  LOOP  THEN ;
 
Directional Recursive Bubble Sort on the stack.

   VARIABLE DIRECTION
 : ASCENDING   DIRECTION ON  ; 
 : DESCENDING  DIRECTION OFF ;
 : COMPARE  DIRECTION @ IF  < ELSE > THEN ;
 
 : BUBBLE  ( n n n ...  m m m ...  one pass )  RECURSIVE
         CR  ." ENTERING " .S
         DEPTH 1 >
         IF   2DUP COMPARE IF SWAP THEN
              >R   BUBBLE   R>
         THEN
         CR  ." LEAVING "  .S ;
 
 : SORT ( n n n n ...    m m m m ... sorted )
         DEPTH 1 > IF
         DEPTH 1-  0 DO  BUBBLE  LOOP  THEN ;

Ŀ
  End of Lesson 7  Part 18   

