Level 4, lesson 9

# 4.9 Recursion

Yes, but can she do recursion? Of course she can! It is even very natural and easy. Everybody knows how to calculate a factorial. In 4tH you can do this by:

         : factorial          ( n1 -- n2)
               dup 2 >
               if
                    dup 1-
                    factorial *
               then
         ;

         10 factorial . cr

Which is exactly as one would expect. Unfortunately, this is not the way it is done in ANS-Forth. In order to let a colon-definition call itself, you have to use the word 'RECURSE'. 4tH supports this word too:

         : factorial          ( n1 -- n2)
               dup 2 >
               if
                    dup 1-
                    recurse *
               then
         ;

         10 factorial . cr

It will even compile to the same code. If you use the word 'RECURSE' outside a colon-definition, the results are undefined. Note that recursion lays a heavy burden on the return stack. Sometimes it is wiser to implement such a routine differently:

         : factorial
               dup

               begin
                    dup 2 >
               while
                    1- swap over * swap
               repeat

               drop
         ;

         10 factorial . cr

So if you ever run into stack errors when you use recursion, keep this in mind.