Loops/Foreach: Difference between revisions

Content added Content deleted
(Add CLU)
Line 1,273: Line 1,273:
: .array ( a len -- )
: .array ( a len -- )
cells bounds do i @ . cell +loop ; \ 3 2 1</lang>
cells bounds do i @ . cell +loop ; \ 3 2 1</lang>
===FOREACH===
<lang forth>\ This thing about extendable languages is if you need FOREACH, you can have FOREACH
\ The Forth ' operator returns the "execution token" (XT) of a Forth word. An XT can be run with EXECUTE.
\ If we apply an appropriate execution to all the elements of an array we have it.

: FOREACH ( array size XT --)
>R \ save execution token on return stack
CELLS BOUNDS \ covert addr len -> last first addresses
BEGIN
2DUP > \ test addresses
WHILE ( last>first )
DUP R@ EXECUTE \ apply the execution token to the address
CELL+ \ move first to the next memory cell
REPEAT
R> DROP \ clean return stack
2DROP \ and data stack
;

\ Make an operator to fetch contents of an address and print
: ? ( addr --) @ . ;

CREATE A[] 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ,

\ Usage example:
A[] 10 ' ? FOREACH


=={{header|Fortran}}==
=={{header|Fortran}}==