Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forth: Portable indefinite loop with multiple exit points

Tags:

loops

forth

I need to implement an idefinite loop with multiple exit points. Unfortunately the most obvious solution - REPEAT - UNTIL with multiple WHILE doesn't work neither in Gforth nor in swapforth (Of course the loop in the example below may be implemented with DO - LOOP. However, that code is just a demonstration. The real problem is related to hardware control in an embedded system, so the loop indeed must be indefinite):

: test1 ( step -- step count )
    0
    begin
      over +
      dup .
      dup 20 < while
      dup 13 = while
    repeat
;

3 test1 

In "Thinking Forth" there is Moore's statement quoted:

Many times conditionals are used to get out of loops. That particular use can be avoided by having loops with multiple exit points. This is a live topic, because of the multiple WHILE construct which is in poly- Forth but hasn’t percolated up to Forth ’83. It’s a simple way of defining multiple WHILEs in the same REPEAT. Also Dean Sanderson [of Forth, Inc.] has invented a new construct that introduces two exit points to a DO LOOP. Given that construction you’ll have fewer tests.

Unfortunately I failed to find the Dean's solution. Is there any portable way to implement multiple exit points in the indefinite loop in Forth?

like image 350
wzab Avatar asked Jul 31 '16 14:07

wzab


People also ask

Can a loop have multiple exit points?

The multiple exit loop construct is a control struc- ture which appears frequently in programming problems and which otherwise can only be realized using state variables and/or goto statements. Using this construct clarifies the program structure, and allows easy correct- ness proofs as well as code optimization.

Which loop is indefinite loop?

An indefinite loop is a loop that waits for some condition to become true. In general, it's not obvious how many iterations it takes. For example, you might be looking for the first number that is divisible by 2, 3, 5, 7, and 11. You could compute this ahead of time, but it's not easy.

Which type of loop has a definite beginning and end and steps from beginning to end?

A for-loop is a set of instructions that is repeated, or iterated, for every value in a sequence. Sometimes for-loops are referred to as definite loops because they have a predefined begin and end as bounded by the sequence.


1 Answers

EXIT of course provides multiple exits to a definition. You can make the body of the loop one and the same with a definition either by having a separate word or, more neatly, by using quotations:

: test ( start step -- count step )
  swap [: begin
    over + dup .
    dup 20 > if ." >20" exit then
    dup 13 = if ." =13" exit then
    dup 17 = if ." =17" exit then
  again ;] execute
  ( EXITs from loop continue here ) ;
like image 113
Julian Fondren Avatar answered Sep 28 '22 11:09

Julian Fondren