Last active
December 18, 2020 17:48
-
-
Save joedougherty/3cd37eb20d7ab5c59bf5072ae5320a68 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
( in this example I use "TOS" to mean "Top of Stack" ) | |
( Here is a one-line word, `f`, that computes the nth fibonacci number. ) | |
: f 0 1 rot 1 ?DO swap over + LOOP swap . ; | |
10 f . ( compute the 10th fibonacci number. ) | |
( `.` pops the computed fibonacci number off the stack and prints it. ) | |
( the stack is empty once again. ) | |
( Here is a heavily annotated version of the same functionality. ) | |
( Note the addition of the `next2fibs` word to increase readability in the `fib` loop. ) | |
: next2fibs | |
( copy the bottom fib to TOS ) | |
swap over | |
( add top two values. now top, bottom are fib on TOS ) | |
+ | |
; | |
: fib ( define the word `fib` ) | |
0 1 ( push the first two fibs on TOS. 0 is the bottom fib number. 1 is the top fib number.) | |
rot 1 ( use `rot` [rotate] to grab the val below the 2 fibs. This value is used in initiating the loop. ) | |
( recall: prior to calling `fib`, the user pushed an int onto the stack. ) | |
( that int denotes which fibonacci number it should produce. ) | |
?DO ( loop _from_ 1 _to_ the value pushed on the stack prior to calling `f` ) | |
( `10 fib`: this will loop from 1 to to 10 ) | |
next2fibs | |
LOOP | |
swap . ( drop the bottom fib, leaving the top fib on TOS) | |
; | |
( this produces the same result as `10 f .` on line 6 ) | |
10 fib . |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment