[comp.lang.forth] Recursion vs. redefinition

wmb@SUN.COM (Mitch Bradley) (05/10/89)

> I do not agree with this reasoning. It seems like redefining a word in
> terms of itself is a more unusual case than is recursion.

Redefinition is extremely useful.  The reason it seems unusual is that
most languages don't allow it.  In my 8 years of serious Forth programming,
I have used recursion perhaps 3 or 4 times (and 2 of those were mutual
recursion where having the word call itself wasn't the right thing anyway).
In contrast, I have used redefinition maybe a zillion times (maybe even
2 zillion).

Here is one of my favorite uses for redefinition:

The problem:  you have several modules each of which need to be initialized.
You don't want to have a master word which initializes each module in turn,
because that requires you to change that word every time you decide to
add or delete a module from the application.   The solution:  an
initialization chain.  First you define:

   : init  ( -- )   ;

Then, within each module, you write that module's initialization code as
follows:

  : init  ( -- )  init  <module-specific initialization code>  ;


Finally, when the time comes to initialize the application, you use
FIND to locate the most recent definition of INIT and then EXECUTE it.

Instant linked lists!

The same technique works for module-specific cleanup (shutdown) code, except
that you generally want to cleanup in the reverse order, i.e.

: cleanup  ( -- )  <module-specific cleanup code>  cleanup  ;


Mitch Bradley