Skip to content

4.) Example Programs

Alexander Schneider edited this page Jan 22, 2015 · 1 revision

##Range/Slice notation:

For the purpose of this description

  • A range is a list of numbers at a regularly spaced interval, bounded by x inclusive on the low side, and y exclusive on the high side, I.E. [x, y).
  • A slice is a 1 to 1 mapping of a range to an ordered collection of elements, such that the index of an element in a slice corresponds to a number given by the range.
  • For brevity and readability, newlines will be represented by ", "

Because they refer to similar concepts, ranges and slice notations use similar syntax.

By itself, a range will return a list. The syntax for that is as follows:

x..y
OR
x..y by z

Where x is the lower bound, inclusive, y is the upper bound, exclusive, and the by z is an optional suffix to the range notation that delimits the "skip" factor (I.E. the interval between numbers or items).

One can use this in a for loop as follows:

for i in 0..5:
  out(i) # will print out 0, 1, 2, 3, 4
end
for i in 0..10 by 2:
  out(i) # will print out 0, 2, 4, 6, 8
end

Alternatively, the range can be assigned to a variable

x := 0..10 by 2 # x will contain the list represented by [0, 2, 4, 6, 8]
y := 0..5 # y will contain the list represented by [0, 1, 2, 3, 4]

Slice notation is similar. A slice will select elements out of an ordered iterable preceding it and return an iterable of the same type, with only the selected elements. This can also be used in a for loop or in a standalone variable declaration as follows:

For loop:

for i in "xylophones"[3..6]:
  out(i) # will print out "o", "p", "h"
end
for i in "xylophones"[0..5 by 3]:
  out(i) # will print out "x", "o"
end

Variable declarations:

x := "xylophones"[3..6] # x equals "oph"
y := [1, 6, 3, 5, 8, 9][1..6 by 2] # y equals [6, 5, 9]