diff options
author | Grzegorz Adam Hankiewicz <gradha@imap.cc> | 2013-01-21 18:25:45 +0100 |
---|---|---|
committer | Grzegorz Adam Hankiewicz <gradha@imap.cc> | 2013-01-21 18:26:34 +0100 |
commit | 958f20aa1ab5c511de73eb397be5fa8d0f0ff085 (patch) | |
tree | e364b9e81be5768139514c6e54e2565a8333dadd /doc | |
parent | d0bd5d5cc3407e14ff37590077ec40441be26c84 (diff) | |
download | Nim-958f20aa1ab5c511de73eb397be5fa8d0f0ff085.tar.gz |
Documents two-variable for loop with sequences.
Diffstat (limited to 'doc')
-rwxr-xr-x | doc/tut1.txt | 25 |
1 files changed, 25 insertions, 0 deletions
diff --git a/doc/tut1.txt b/doc/tut1.txt index 2ae7e9540..aead6e36e 100755 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -349,6 +349,7 @@ provides. The example uses the built-in ``countup`` iterator: echo("Counting to ten: ") for i in countup(1, 10): echo($i) + # --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines The built-in ``$`` operator turns an integer (``int``) and many other types into a string. The variable ``i`` is implicitly declared by the ``for`` loop @@ -362,6 +363,7 @@ the same: while i <= 10: echo($i) inc(i) # increment i by 1 + # --> Outputs 1 2 3 4 5 6 7 8 9 10 on different lines Counting down can be achieved as easily (but is less often needed): @@ -369,6 +371,7 @@ Counting down can be achieved as easily (but is less often needed): echo("Counting down from 10 to 1: ") for i in countdown(10, 1): echo($i) + # --> Outputs 10 9 8 7 6 5 4 3 2 1 on different lines Since counting up occurs so often in programs, Nimrod also has a ``..`` iterator that does the same: @@ -1202,6 +1205,28 @@ raised) for performance reasons. Thus one should use empty sequences ``@[]`` rather than ``nil`` as the *empty* value. But ``@[]`` creates a sequence object on the heap, so there is a trade-off to be made here. +The ``for`` statement can be used with one or two variables when used with a +sequence. When you use the one variable form, the variable will hold the value +provided by the sequence. The ``for`` statement is looping over the results +from the ``items()`` iterator from the `system <system.html>`_ module. But if +you use the two variable form, the first variable will hold the index position +and the second variable will hold the value. Here the ``for`` statement is +looping over the results from the ``pairs()`` iterator from the `system +<system.html>`_ module. Examples: + +.. code-block:: nimrod + for i in @[3, 4, 5]: + echo($i) + # --> 3 + # --> 4 + # --> 5 + + for i, value in @[3, 4, 5]: + echo("index: ", $i, ", value:", $value) + # --> index: 0, value:3 + # --> index: 1, value:4 + # --> index: 2, value:5 + Open arrays ----------- |