Skip to content

ranges_proposal

Matěj Štágl edited this page May 9, 2022 · 2 revisions

Ranges proposal

Ranges represent a sequence of ordered integers n, n+1.. m where n <= m. They can be used as iterables and should support protomethods.
Lower and upper bounds are exposed via properties From and To respectively.

Operators

To create a new range, one of the four following operators can be used:

  • .. - closed range (inclusive on both bounds)
  • ..< - half open range (inclusive on lower bound)
  • >.. - half closed range (inclusive on upper bound)
  • >..< - closed range (exclusive on both bounds)

this proposal also removes previous usage of .. operator as string exclusive concatenation from Wattle.

Working with ranges

Ranges can be stored within variables. DynValue.NewRange(Range range) can be used to construct a range C# side. Unlike Swift, ranges with lower bound being higher than the high bound are legal. Enumerating such range results in an empty enumerator.

myRange = 2..1

for (i in myRange) {
 // this won't trigger
}

Standard library

A new WattleScriptModule for ranges should be introduced.

range.explode(range) // takes a range and costructs a table from it 1..5 would yield [1, 2, 3, 4, 5]. 5..1 would return [].
range.sort(range) // takes a range and if low bound is higher than the high bound, bounds are swapped. Otherwise noop. 1..5 -> 1..5, 5..1 -> 1..5.
range.sum(range) // takes a range and returns sum of low and high bounds. 1..10 -> 11
range.reverse(range) // takes a range and always swaps low and high bounds. 1..5 -> 5..1, 5..1 -> 1..5
range.max(range) // takes a range and returns higher from the bounds. 1..5 -> 5, 5..1 -> 5
range.min(range) // same but with lower bounds

Once protomethods are available these should be working as protomethods as well.