mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 09:41:36 +00:00
[forth/en] Clarify bounds of do and the difference between ?do vs do (#4058)
* Clarify bounds of do and ?do vs do * Re-introduce square into example --------- Co-authored-by: ven <vendethiel@hotmail.fr>
This commit is contained in:
parent
79538b5bcb
commit
be771f6c2e
@ -93,8 +93,8 @@ see square \ : square dup * ; ok
|
|||||||
|
|
||||||
\ ------------------------------------ Loops -----------------------------------
|
\ ------------------------------------ Loops -----------------------------------
|
||||||
|
|
||||||
\ `do` is also a compile-only word.
|
\ `?do` is also a compile-only word.
|
||||||
: myloop ( -- ) 5 0 do cr ." Hello!" loop ; \ ok
|
: myloop ( -- ) 5 0 ?do cr ." Hello!" loop ; \ ok
|
||||||
myloop
|
myloop
|
||||||
\ Hello!
|
\ Hello!
|
||||||
\ Hello!
|
\ Hello!
|
||||||
@ -102,16 +102,17 @@ myloop
|
|||||||
\ Hello!
|
\ Hello!
|
||||||
\ Hello! ok
|
\ Hello! ok
|
||||||
|
|
||||||
\ `do` expects two numbers on the stack: the end number and the start number.
|
\ `?do` expects two numbers on the stack: the end number (exclusive) and the
|
||||||
|
\ start number (inclusive).
|
||||||
|
|
||||||
\ We can get the value of the index as we loop with `i`:
|
\ We can get the value of the index as we loop with `i`:
|
||||||
: one-to-12 ( -- ) 12 0 do i . loop ; \ ok
|
: one-to-12 ( -- ) 12 0 do i . loop ; \ ok
|
||||||
one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 ok
|
one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 ok
|
||||||
|
|
||||||
\ `?do` works similarly, except it will skip the loop if the end and start
|
\ `do` works similarly, except if start and end are exactly the same it will
|
||||||
\ numbers are equal.
|
\ loop forever (until arithmetic underflow).
|
||||||
: squares ( n -- ) 0 ?do i square . loop ; \ ok
|
: loop-forever 1 1 do i square . loop ; \ ok
|
||||||
10 squares \ 0 1 4 9 16 25 36 49 64 81 ok
|
loop-forever \ 1 4 9 16 25 36 49 64 81 100 ...
|
||||||
|
|
||||||
\ Change the "step" with `+loop`:
|
\ Change the "step" with `+loop`:
|
||||||
: threes ( n n -- ) ?do i . 3 +loop ; \ ok
|
: threes ( n n -- ) ?do i . 3 +loop ; \ ok
|
||||||
|
Loading…
Reference in New Issue
Block a user