From ac8ab4c54967a83d800655d9de42ece7d5e21c93 Mon Sep 17 00:00:00 2001 From: Kaushal Modi Date: Fri, 19 Jun 2020 10:22:48 -0400 Subject: [PATCH] Clarify the use of the backwards index operator (^N) in tut1 (#14681) * Clarify the use of the backwards index operator (^N) in tut1 For consistency: - Do `[a .. ^b]` (notice spaces on both sides of `..`) - Do `[c ..< d]` (notice spaces on both sides of `..<`) Fixes https://github.com/nim-lang/Nim/issues/14671. * tut1: Add a note that ^ template calls can be saved to consts --- doc/tut1.rst | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/doc/tut1.rst b/doc/tut1.rst index 6d54d88a38..24874096c7 100644 --- a/doc/tut1.rst +++ b/doc/tut1.rst @@ -395,20 +395,29 @@ Since counting up occurs so often in programs, Nim also has a `.. `_ iterator that does the same: .. code-block:: nim - for i in 1..10: + for i in 1 .. 10: ... -Zero-indexed counting have two shortcuts ``..<`` and ``..^`` to simplify counting to one less than the higher index: +Zero-indexed counting has two shortcuts ``..<`` and ``.. ^1`` +(`backwards index operator `_) to simplify +counting to one less than the higher index: .. code-block:: nim - for i in 0..<10: - ... # 0..9 + for i in 0 ..< 10: + ... # 0 .. 9 or .. code-block:: nim var s = "some string" - for i in 0.. 'a prog' - b[11..^2] = "useful" + echo a[7 .. 12] # --> 'a prog' + b[11 .. ^2] = "useful" echo b # --> 'Slices are useful.' In the previous example slices are used to modify a part of a string. The @@ -1425,17 +1434,22 @@ indices are 0 11 17 using indices ^19 ^8 ^2 using ^ syntax -where ``b[0..^1]`` is equivalent to ``b[0..b.len-1]`` and ``b[0..`_. In the above example, because the string ends in a period, to get the portion of the string that is "useless" and replace it with "useful". -``b[11..^2]`` is the portion "useless", and ``b[11..^2] = "useful"`` replaces the +``b[11 .. ^2]`` is the portion "useless", and ``b[11 .. ^2] = "useful"`` replaces the "useless" portion with "useful", giving the result "Slices are useful." -Note: alternate ways of writing this are ``b[^8..^2] = "useful"`` or -as ``b[11..b.len-2] = "useful"`` or as ``b[11..`_ +of type ``BackwardsIndex``, we can have a ``lastIndex`` constant defined as ``const lastIndex = ^1``, +and later used as ``b[0 .. lastIndex]``. Objects -------