11.8 Recursion. 4tH 4tH Forth compiler
Anuncio
Anuncio
CHAPTER 11. ADVANCED PROGRAMMING
11.8
Recursion
143
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:
( n1 -- n2) : factorial dup 2 > if dup 1factorial * 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:
( n1 -- n2) : factorial dup 2 > if dup 1recurse * then
;
10 factorial . cr
It will even compile to the same code. If you use the word ’RECURSE’ outside a colondefinition, 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.
11.9
Private declarations
Sometimes you want to hide some definitions from other programmers. This is especially true when you’re writing libraries or templates. The Application Programmers Interface must be public of course, but you don’t want anyone else to tinker with the internals of your library. And there is the problem of cluttering your name space.
Relax, 4tH has a way to get rid of these internal words. It’s easy, just tell 4tH to hide them:
Descargar
Anuncio