home *** CD-ROM | disk | FTP | other *** search
-
- ╔═════════════════════════════════════════════════════╗
- ║ Lesson 7 Part 170 F-PC 3.5 Tutorial by Jack Brown ║
- ╚═════════════════════════════════════════════════════╝
-
-
- More examples of recursive definitions. Remove the lines at the beginning
- and end of each definition that print the stack once you understand what
- is going on.
- ┌─────────────────────────────────────┐
- │ Recursive Definition of Factorial │
- └─────────────────────────────────────┘
- FACTORIAL
- Recursive definition: n! = n(n-1)! where 0! = 1
- Examples: 5! = 5*4!
- Algorithm:
- To fine n!:
- Examine n
- IF ( n is not zero )
- call myself with n-1
- multiply result by n
- ELSE ( n is zero )
- return result of 1
- THEN
- End of n!;
-
- Program for n!
- : FACTORIAL ( n -- n! ) RECURSIVE
- CR ." Entering factorial" .S
- DUP IF ( n is not zero )
- DUP 1- FACTORIAL *
- ELSE ( n is zero )
- DROP 1
- THEN
- CR ." Leaving factorial" .S ;
-
- If you try this with negative n you will be sorry! Fix it so an error
- message is given if negative is on stack. What is the largest factorial
- you can calculate with this definition? Implement FACTORIAL using double
- numbers. Hint: you need D* If you don't have it is on the FORTH Board
- in Area 2 !
-
- ┌──────────────────────────────────────────┐
- │ Recursive Definition of Power Function │
- └──────────────────────────────────────────┘
-
- Power function 2^n
- Definition: 2^n = 2*2^(n-1) if n=0 2^n = 1
- Algorithm:
- To find 2^n:
- Examine n
- IF ( n not zero) call myself with argument n-1
- and multiply the result by 2
- ELSE ( n is zero ) just return with 1 for the answer.
- THEN End of 2^n;
-
- Program:
- : 2^n ( n -- 2^n ) RECURSIVE
- CR ." Entering" .S
- DUP 0> IF 1- 2^n 2*
- ELSE DROP 1
- THEN
- CR ." Leaving " .S ;
-
- ┌─────────────────────────────────────────────┐
- │ Recursive Definition of Fibonacci Numbers │
- └─────────────────────────────────────────────┘
-
- The famous Fibonacci numbers!
- 0 1 1 2 3 5 8 13 21 34 etc
- Definition: F(n) = F(n-1) + F(n-2) for n > 1
- F(n) = n if n = 0 or 1
- Wow! this one is doubly recursive.
-
- Here is the program. You reconstruct the word algorithm.
- : FIBONACCI ( n Fn ) RECURSIVE
- CR ." entering" .S
- DUP 0< ABORT" invalid argument"
- DUP 1 >
- IF DUP 1- FIBONACCI
- SWAP 2- FIBONACCI +
- ELSE ( nothing to do as we have a 1 or 0 )
- THEN
- CR ." leaving " .S ;
-
- ┌───────────────────────────────────┐
- │ Please Move to Lesson 7 Part 180 │
- └───────────────────────────────────┘
-
-