Intervals

Now, we afford one of the most powerful features of Scriptol, ranges. Ranges are used only by old classical languages in the "for" control structure, and in other modern languages, they may be used with different syntaxes according to the context. In Scriptol the concept is unified and the same syntax is used for any kind of range. This is a couple of indices linked by two points: start .. end.

0 .. 10
x .. y
x * 2 / 4 .. y + 10

and so ones.
You can write also:
[x..] that means: from x to the end, and
[..y] that means: from the begin to y included.

You may use range to test if a value is inside a list:
if x in 10..100
You may use it to scan a list:
for x in 1..100
You may extract a part of a list:
array b = a[x..y]
And finally, you may change a part of a list:
a[x..y] = another list

For now we will study only subscripting of array or dict (and not texts). The syntax is the name for the two ones as we are using positions and not keys.

// Creating a list:

array a = array(x0, x1, x2, x3, x4, x5, x6, x7, x8)

//Splitting the list into three ones:
array b = a[ .. 2]
array c = a[3 .. 5]
array d = a[6 .. ]

/*
Now we have three arrays, with these contents:
a: (x0, x1, x2)
b: (x3, x4, x5)
c: (x6, x7, x8)
*/


// Displaying the arrays:
b.display()

// etc...

array (
 [0] => x0
 [1] => x1
 [2] => x2
)


and so ones...

To replace an interval by another list, a simple assignment is required:

  a[3..5] = array("a", "b", "c")


The content should become: (x0, x1, x2, "a", "b", "c", x6, x7, x8)

A sub-list may be replaced either by another list, or by a single value, the syntax is the same:

   a[3..5] = "xyz"

The list becomes: (x0, x1, x2, "xyz", x6, x7, x8)

If we want rather to remove a sub-list from the original array, we have to declare it "not in list" and the syntax is simply:

  a[3..5] = nil

As we have removed the sub-list 3..5 that is (x3, x4, x5), the content now becomes: (x0, x1, x2, x6, x7, x8)

In the same manner we can test if a value is inside a list, we can perform the test on a sub-list, for example:

array a = array("one, "two", "three")
if "two" in a[2..5] print "inside"


We have sawn above how to test if a list is a part of another one, thanks to the "&" operator. Let us perform the same with sub-lists:

array asub = a[2..3]
if (asub & b[6..8]) = asub) print "inside"



 Exercises

 

1) From this array:
array a = array("ace", "king", "queen", "knight", "10")
extract the sub-array from ace to knight and put it into the b array.
Element can be localized with the find(text) method that return the position.

Answer