home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / forth / compiler / fpc / tutor / l7p180 < prev   
Text File  |  1990-07-15  |  2KB  |  64 lines

  1.  
  2.        ╔═════════════════════════════════════════════════════╗
  3.        ║  Lesson 7 Part 180 F-PC 3.5 Tutorial by Jack Brown  ║
  4.        ╚═════════════════════════════════════════════════════╝
  5.  
  6.               ┌─────────────────────────────────────┐
  7.               │  Recursive Greatest Common Divisor  │
  8.               └─────────────────────────────────────┘
  9.  
  10. The greatest common divisor of two numbers a and b is the largest number
  11. n that will divide into both a and b. Here is the recursive definition,
  12. you figure out how it works
  13.  
  14.  :  GCD   ( a b -- n )   RECURSIVE
  15.          CR ." Entering " .S
  16.          DUP  IF   SWAP OVER MOD GCD
  17.               ELSE DROP
  18.               THEN
  19.          CR ." Leaving " .S ;
  20.  
  21.               ┌───────────────────────────────────────┐
  22.               │  Recursive Bubble Sort on the Stack.  │
  23.               └───────────────────────────────────────┘
  24.  
  25. \ BUBBLE does one pass.  It is the recursive word!
  26.  
  27.  : BUBBLE  ( n n n ...  m m m ...  one pass )  RECURSIVE
  28.          CR  ." ENTERING " .S
  29.          DEPTH 1 >
  30.          IF   2DUP  <  IF SWAP THEN
  31.               >R   BUBBLE   R>
  32.          THEN
  33.          CR  ." LEAVING "  .S ;
  34.  
  35.  You can get rid of the entering and leaving .
  36.  To use: put any numbers on the stack and type SORT
  37.  
  38.  : SORT ( n n n n ...    m m m m ... sorted )
  39.          DEPTH 1 > IF
  40.          DEPTH 1-  0 DO  BUBBLE  LOOP  THEN ;
  41.  
  42. Directional Recursive Bubble Sort on the stack.
  43.  
  44.    VARIABLE DIRECTION
  45.  : ASCENDING   DIRECTION ON  ; 
  46.  : DESCENDING  DIRECTION OFF ;
  47.  : COMPARE  DIRECTION @ IF  < ELSE > THEN ;
  48.  
  49.  : BUBBLE  ( n n n ...  m m m ...  one pass )  RECURSIVE
  50.          CR  ." ENTERING " .S
  51.          DEPTH 1 >
  52.          IF   2DUP COMPARE IF SWAP THEN
  53.               >R   BUBBLE   R>
  54.          THEN
  55.          CR  ." LEAVING "  .S ;
  56.  
  57.  : SORT ( n n n n ...    m m m m ... sorted )
  58.          DEPTH 1 > IF
  59.          DEPTH 1-  0 DO  BUBBLE  LOOP  THEN ;
  60.  
  61. ┌─────────────────────────────┐
  62. │  End of Lesson 7  Part 18   │
  63. └─────────────────────────────┘
  64.