Skip to content

Instantly share code, notes, and snippets.

@metaperl
Created March 6, 2010 22:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metaperl/323976 to your computer and use it in GitHub Desktop.
Save metaperl/323976 to your computer and use it in GitHub Desktop.
gForth examples improved
\ http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/General-Loops-Tutorial.html
: halve-n ( n -- n/2 ) 2/ ;
: init-counter-for-number-of-halves-needed ( -- 0 ) 0 ;
: insure-n-is-greater-than-or-equal-to-0 ( n counter -- n counter flag )
over 0> ;
: halve-n-and-increment-counter { n counter -- n/2 counter+1 }
n 2/ counter 1+ ;
: log2 ( +n1 -- n2 )
assert( dup 0> )
halve-n
init-counter-for-number-of-halves-needed
BEGIN
insure-n-is-greater-than-or-equal-to-0
WHILE \ n >= 0
halve-n-and-increment-counter
REPEAT
NIP \ n, leaving the counter
;
\ http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Counted-loops-Tutorial.html
: ^ { n power }
n 1 power 0
U+DO
OVER *
LOOP
NIP ;
\ http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Counted-loops-Tutorial.html
: fac { u -- u! }
1 \ seed the factorial multiplication
u 1+ 1 U+DO \ loop over range [1,u+1)
i *
LOOP ;
\ recursion
: fib { n -- fibn }
assert( n 0>= )
n CASE
0 OF 0 ENDOF
1 OF 1 ENDOF
2 OF 1 ENDOF
( otherwise ) n 1 - recurse n 2 - recurse +
SWAP ENDCASE ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment