compilationcontrol-flowforthgforthimmediate-mode

Examples of Custom Control Flow Compiling Words


Forth famously allows users to alter the language by defining new words for control flow (beyond those given by the standard: DO, LOOP, BEGIN, UNTIL, WHILE, REPEAT, LEAVE IF, THEN, ELSE, CASE, ENDCASE, etc.)

Are there common examples of people actually creating their own new control flow words? What are some typical and useful examples? Or has the standard already defined everything that people actually need?

I'm hoping to find examples of useful language extensions that have gained acceptance or proved generally helpful to make the language more expressive.


Solution

  • One another big direction of control flow structures in Forth is backtracking. It is very expressive and powerful mechanism. To be implemented, it requires return address manipulation [Gas99].

    Backtracking in Forth was developed as BacFORTH extension by M.L.Gassananko in ~1988-1990. First papers on this topic was in Russian.

    The technique of backtracking enables one to create abstract iterator and filter modules responsible for looking over sets of all possible values and rejecting "undue" ones [Gas96b].

    For some introduction see the short description: Backtracking (by mlg), also the multi-threading in Forth? discussion in comp.lang.forth can be useful (see the messages from Gassanenko).

    Just one example of generator in BacFORTH:

    : (0-2)=> PRO 3 0 DO I CONT LOOP ; \ generator
    : test  (0-2)=>  CR . ." : " (0-2)=>  .  ;
    test CR
    

    Output:

    0 : 0 1 2
    1 : 0 1 2
    2 : 0 1 2
    

    The PRO and CONT are special control flow words. PRO designates generator word, and CONT calls the consumer — it is something like yield in Ruby or ECMAScript. A number of other special words is also defined in BacFORTH. You can play with BacFORTH in SP-Forth (just include ~profit/lib/bac4th.f library).

    Etymology

    In general, backtracking is just an algorithm for finding solutions. In Prolog this algorithm was embedded under the hood, so backtracking in Prolog is the process how it works themselves. Backtracking in BacFORTH is programming technique that is supported by a set of special control flow words.

    References