www.delorie.com/gnu/docs/gforth/gforth_32.html   search  
 
Buy GNU books!


Gforth Manual

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.20 Recursion

Usually the name of a definition is not visible in the definition; but earlier definitions are usually visible:

 
1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
: / ( n1 n2 -- n )
  dup 0= if
    -10 throw \ report division by zero
  endif
  /           \ old version
;
1 0 /

For recursive definitions you can use recursive (non-standard) or recurse:

 
: fac1 ( n -- n! ) recursive
 dup 0> if
   dup 1- fac1 *
 else
   drop 1
 endif ;
7 fac1 .

: fac2 ( n -- n! )
 dup 0> if
   dup 1- recurse *
 else
   drop 1
 endif ;
8 fac2 .

Assignment:
Write a recursive definition for computing the nth Fibonacci number.

Reference (including indirect recursion): See section 5.8.5 Calls and returns.


  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003