What are ranges?

Ranges are an extension of the index operator. Rather than specifying a single integer index, a range takes a lower and, optionally, an upper bound. Ranges also support negative bounds which are interpreted to be indexes "from the end." Lower bounds are inclusive, upper bounds are exclusive. Upper bounds are optional. Bounds can be "overshot." Specifying an upper bound that is too big is corrected automatically to the maximum legal upper bound. Specifying a lower bound exceeding the size of the input will result in an empty result.

Some examples are probably the best way of explaining how ranges work.

C:\terp\bin>terp -e "{1,2,3,4,5,6}[0]"                  (1)
C:\terp\bin>terp -e "{1,2,3,4,5,6}[0..2]"               (2)
C:\terp\bin>terp -e "{1,2,3,4,5,6}[3..]"                (3)
C:\terp\bin>terp -e "{1,2,3,4,5,6}[-2..]"               (4)
C:\terp\bin>terp -e "{1,2,3,4,5,6}[0..-1]"              (5)
C:\terp\bin>terp -Ex=3 -e "{1,2,3,4,5,6}[x..-1]"        (6)

The first example is a simple index operator which selects the first element in the list. The index operator internally delegates to the range operator by interpreting the index as the lower bound and adding 1 to it to form the upper bound.

The second example selects the first two elements (from 0 inclusive to 2 exclusive) and returns them as a sublist. In the evaluated examples, the sublist is then converted to a string by concatenating the elements, which is why you end up with the string "12".

The third example selects the elements from index 3 inclusive to the end. This is an example of a range without an upper bound.

The fourth example selects the elements starting with the second to last and ending with the last. Negative indices are interpreted as "n from the end".

The fifth example selects the sublist from the beginning (inclusive) to the end (exclusive).

The sixth and final example illustrates that you can use unary expressions in the bounds.

Ranges can be applied to collections and strings. In the case of strings, they always return a string, even if the string consists of no characters or one character.

Copyright 2006-2016 by Codemesh, Inc., ALL RIGHTS RESERVED

terp expressions
codemesh.com home expressions templates ant about us contact us download