Module std.range
This module defines the notion of a range. Ranges generalize the concept of
arrays, lists, or anything that involves sequential access. This abstraction
enables the same set of algorithms (see std) to be used
with a vast variety of different concrete types. For example,
a linear search algorithm such as find
works not just for arrays, but for linked-lists, input files,
incoming network data, etc.
Guides
There are many articles available that can bolster understanding ranges:
- Ali Çehreli's tutorial on ranges for the basics of working with and creating range-based code.
- Jonathan M. Davis Introduction to Ranges talk at DConf 2015 a vivid introduction from its core constructs to practical advice.
- The DLang Tour's chapter on ranges for an interactive introduction.
- H. S. Teoh's tutorial on component programming with ranges for a real-world showcase of the influence of range-based programming on complex algorithms.
- Andrei Alexandrescu's article On Iteration for conceptual aspect of ranges and the motivation
Submodules
This module has two submodules:
The std submodule
provides basic range functionality. It defines several templates for testing
whether a given object is a range, what kind of range it is, and provides
some common range operations.
The std submodule
provides object-based interfaces for working with ranges via runtime
polymorphism.
The remainder of this module provides a rich set of range creation and composition templates that let you construct new ranges out of existing ranges:
| chain | Concatenates several ranges into a single range. | 
| choose | Chooses one of two ranges at runtime based on a boolean condition. | 
| chooseAmong | Chooses one of several ranges at runtime based on an index. | 
| chunks | Creates a range that returns fixed-size chunks of the original range. | 
| cycle | Creates an infinite range that repeats the given forward range indefinitely. Good for implementing circular buffers. | 
| drop | Creates the range that results from discarding the first n elements from the given range. | 
| dropBack | Creates the range that results from discarding the last n elements from the given range. | 
| dropExactly | Creates the range that results from discarding exactly n of the first elements from the given range. | 
| dropBackExactly | Creates the range that results from discarding exactly n of the last elements from the given range. | 
| dropOne | Creates the range that results from discarding the first element from the given range. | 
|  | Creates the range that results from discarding the last element from the given range. | 
| enumerate | Iterates a range with an attached index variable. | 
| evenChunks | Creates a range that returns a number of chunks of approximately equal length from the original range. | 
| frontTransversal | Creates a range that iterates over the first elements of the given ranges. | 
| generate | Creates a range by successive calls to a given function. This allows to create ranges as a single delegate. | 
| indexed | Creates a range that offers a view of a given range as though its elements were reordered according to a given range of indices. | 
| iota | Creates a range consisting of numbers between a starting point and ending point, spaced apart by a given interval. | 
| lockstep | Iterates n ranges in lockstep, for use in a foreachloop. Similar tozip, except thatlockstepis designed
        especially forforeachloops. | 
| nullSink | An output range that discards the data it receives. | 
| only | Creates a range that iterates over the given arguments. | 
| padLeft | Pads a range to a specified length by adding a given element to the front of the range. Is lazy if the range has a known length. | 
| padRight | Lazily pads a range to a specified length by adding a given element to the back of the range. | 
| radial | Given a random-access range and a starting point, creates a range that alternately returns the next left and next right element to the starting point. | 
| recurrence | Creates a forward range whose values are defined by a mathematical recurrence relation. | 
| refRange | Pass a range by reference. Both the original range and the RefRange will always have the exact same elements. Any operation done on one will affect the other. | 
| repeat | Creates a range that consists of a single element repeated n times, or an infinite range repeating that element indefinitely. | 
| retro | Iterates a bidirectional range backwards. | 
| roundRobin | Given n ranges, creates a new range that return the n first elements of each range, in turn, then the second element of each range, and so on, in a round-robin fashion. | 
| sequence | Similar to recurrence, except that a random-access range is
        created. | 
|  | Creates a range that returns a fixed-size sliding window over the original range. Unlike chunks, it advances a configurable number of items at a time, not one chunk at a time. | 
| stride | Iterates a range with stride n. | 
| tail | Return a range advanced to within nelements of the end of
        the given range. | 
| take | Creates a sub-range consisting of only up to the first n elements of the given range. | 
| takeExactly | Like take, but assumes the given range actually has n
        elements, and therefore also defines thelengthproperty. | 
| takeNone | Creates a random-access range consisting of zero elements of the given range. | 
| takeOne | Creates a random-access range consisting of exactly the first element of the given range. | 
| tee | Creates a range that wraps a given range, forwarding along its elements while also calling a provided function with each element. | 
| transposed | Transposes a range of ranges. | 
| transversal | Creates a range that iterates over the n'th elements of the given random-access ranges. | 
| zip | Given n ranges, creates a range that successively returns a tuple of all the first elements, a tuple of all the second elements, etc. | 
Sortedness
Ranges whose elements are sorted afford better efficiency with certain
operations. For this, the assumeSorted function can be used to
construct a SortedRange from a pre-sorted range. The sort function also conveniently
returns a SortedRange. SortedRange objects provide some additional
range operations that take advantage of the fact that the range is sorted.
Functions
| Name | Description | 
|---|---|
| 
									assumeSorted(r)
								 | Assumes ris sorted by predicatepredand returns the
correspondingSortedRange!(pred, R)havingras support. To
keep the checking costs low, the cost is Ο(1) in release mode
(no checks for sorted-ness are performed). In debug mode, a few random
elements ofrare checked for sorted-ness. The size of the sample
is proportional Ο(log(r). That way, checking has no
effect on the complexity of subsequent operations specific to sorted
ranges (such as binary search). The probability of an arbitrary
unsorted range failing the test is very high (however, an
almost-sorted range is likely to pass it). To check for sorted-ness at
cost Ο(n), useisSorted. | 
| 
									bitwise(range)
								 | Bitwise adapter over an integral type range. Consumes the range elements bit by bit, from the least significant bit to the most significant bit. | 
| 
									chain(rs)
								 | Spans multiple ranges in sequence. The function chaintakes any
number of ranges and returns aChain!(R1, R2,...)object. The
ranges may be different, but they must have the same element type. The
result is a range that offers thefront,popFront, andemptyprimitives. If all input ranges offer random access andlength,Chainoffers them as well. | 
| 
									choose(condition, r1, r2)
								 | Choose one of two ranges at runtime depending on a Boolean condition. | 
| 
									chooseAmong(index, rs)
								 | Choose one of multiple ranges at runtime. | 
| 
									chunks(source, chunkSize)
								 | This range iterates over fixed-sized chunks of size chunkSizeof asourcerange.Sourcemust be an input range.chunkSizemust be greater than zero. | 
| 
									cycle(input)
								 | Repeats the given forward range ad infinitum. If the original range is
infinite (fact that would make Cyclethe identity application),Cycledetects that and aliases itself to the range type
itself. That works for non-forward ranges too.
If the original range has random access,Cycleoffers
random access and also offers a constructor taking an initial positionindex.Cycleworks with static arrays in addition to ranges,
mostly for performance reasons. | 
| 
									drop(range, n)
								 | Convenience function which calls popFrontN(range, n)and returnsrange.dropmakes it easier to pop elements from a range
    and then pass it to another function within a single expression,
    whereaspopFrontNwould require multiple statements. | 
| 
									dropBack(range, n)
								 | Convenience function which calls popFrontN(range, n)and returnsrange.dropmakes it easier to pop elements from a range
    and then pass it to another function within a single expression,
    whereaspopFrontNwould require multiple statements. | 
| 
									dropBackExactly(range, n)
								 | Similar to dropanddropBackbut they callrangeandrangeinstead. | 
| 
									dropBackOne(range)
								 | Convenience function which calls rangeand returnsrange.dropOnemakes it easier to pop an element from a range
    and then pass it to another function within a single expression,
    whereaspopFrontwould require multiple statements. | 
| 
									dropExactly(range, n)
								 | Similar to dropanddropBackbut they callrangeandrangeinstead. | 
| 
									dropOne(range)
								 | Convenience function which calls rangeand returnsrange.dropOnemakes it easier to pop an element from a range
    and then pass it to another function within a single expression,
    whereaspopFrontwould require multiple statements. | 
| 
									enumerate(range, start)
								 | Iterate over rangewith an attached index variable. | 
| 
									evenChunks(source, chunkCount)
								 | This range splits a sourcerange intochunkCountchunks of
approximately equal length.Sourcemust be a forward range with
known length. | 
| 
									frontTransversal(rr)
								 | Given a range of ranges, iterate transversally through the first elements of each of the enclosed ranges. | 
| 
									generate(fun)
								 | Given callable ( isCallable)fun, create as a range
whose front is defined by successive calls tofun().
This is especially useful to call function with global side effects (random
functions), or to create ranges expressed as a single delegate, rather than
an entirefront/popFront/emptystructure.funmaybe be passed either a template alias parameter (existing
function, delegate, struct type definingstatic opCall) or
a run-time value argument (delegate, function object).
The result range models an InputRange
(isInputRange).
The resulting range will callfun()on construction, and every call topopFront, and the cached value will be returned whenfrontis called. | 
| 
									indexed(source, indices)
								 | This struct takes two ranges, sourceandindices, and creates a view
ofsourceas if its elements were reordered according toindices.indicesmay include only a subset of the elements ofsourceand
may also repeat elements. | 
| 
									iota(begin, end, step)
								 | Creates a range of values that span the given starting and stopping values. | 
| 
									lockstep(ranges)
								 | Iterate multiple ranges in lockstep using a foreachloop. In contrast tozipit allows reference access to its elements. If only a single
   range is passed in, theLockstepaliases itself away.  If the
   ranges are of different lengths ands==StoppingPolicystop after the shortest range is empty.  If the ranges are of different
   lengths ands==StoppingPolicy, throw an
   exception.smay not beStoppingPolicy, and passing this
   will throw an exception. | 
| 
									nullSink()
								 | An OutputRange that discards the data it receives. | 
| 
									only(values)
								 | Assemble valuesinto a range that carries all its
elements in-situ. | 
| 
									padLeft(r, e, n)
								 | Extends the length of the input range rby padding out the start of the
range with the elemente. The elementemust be of a common type with
the element type of the rangeras defined byCommonType.
Ifnis less than the length of ofr, thenris returned unmodified. | 
| 
									padRight(r, e, n)
								 | Extend the length of the input range rby padding out the end of the range
with the elemente. The elementemust be of a common type with the
element type of the rangeras defined byCommonType.
Ifnis less than the length of ofr, then the contents ofrare
returned. | 
| 
									radial(r, startingIndex)
								 | Iterates a random-access range starting from a given point and progressively extending left and right from that point. If no initial point is given, iteration starts from the middle of the range. Iteration spans the entire range. | 
| 
									recurrence(initial)
								 | Creates a mathematical sequence given the initial values and a
recurrence function that computes the next value from the existing
values. The sequence comes in the form of an infinite forward
range. The type Recurrenceitself is seldom used directly; most
often, recurrences are obtained by calling the functionrecurrence. | 
| 
									refRange(range)
								 | Wrapper which effectively makes it possible to pass a range by reference. Both the original range and the RefRange will always have the exact same elements. Any operation done on one will affect the other. So, for instance, if it's passed to a function which would implicitly copy the original range if it were passed to it, the original range is not copied but is consumed as if it were a reference type. | 
| 
									repeat(value)
								 | Create a range which repeats one value. | 
| 
									retro(r)
								 | Iterates a bidirectional range backwards. The original range can be
accessed by using the sourceproperty. Applying retro twice to
the same range yields the original range. | 
| 
									roundRobin(rs)
								 | roundRobin(r1, r2, r3)yieldsr1, thenr2,
thenr3, after which it pops off one element from each and
continues again fromr1. For example, if two ranges are involved,
it alternately yields elements off the two ranges.roundRobinstops after it has consumed all ranges (skipping over the ones that
finish early). | 
| 
									sequence(args)
								 | Sequenceis similar toRecurrenceexcept that iteration is
   presented in the so-called   closed form. This means that thenth element in the series is
   computable directly from the initial values andnitself. This
   implies that the interface offered bySequenceis a random-access
   range, as opposed to the regularRecurrence, which only offers
   forward iteration. | 
| 
									slide(source, windowSize, stepSize)
								 | A fixed-sized sliding window iteration
of size windowSizeover asourcerange by a customstepSize. | 
| 
									stride(r, n)
								 | Iterates range rwith striden. If the range is a
random-access range, moves by indexing into the range; otherwise,
moves by successive calls topopFront. Applying stride twice to
the same range results in a stride with a step that is the
product of the two applications. It is an error fornto be 0. | 
| 
									tail(range, n)
								 | Return a range advanced to within _nelements of the end ofrange. | 
| 
									take(input, n)
								 | Lazily takes only up to nelements of a range. This is
particularly useful when using with infinite ranges. | 
| 
									takeExactly(range, n)
								 | Similar to take, but assumes thatrangehas at leastnelements. Consequently, the result oftakeExactly(range, n)always defines thelengthproperty (and initializes it ton)
even whenrangeitself does not definelength. | 
| 
									takeNone()
								 | Returns an empty range which is statically known to be empty and is
    guaranteed to have lengthand be random access regardless ofR's
    capabilities. | 
| 
									takeNone(range)
								 | Creates an empty range from the given range in Ο( 1). If it can, it
    will return the same range type. If not, it will returntakeExactly(range, 0). | 
| 
									takeOne(source)
								 | Returns a range with at most one element; for example, takeOne([42, 43, 44])returns a range consisting of the integer42. CallingpopFront()off that range renders it empty. | 
| 
									tee(inputRange, outputRange)
								 | Implements a "tee" style pipe, wrapping an input range so that elements of the
  range can be passed to a provided function or OutputRangeas they are
  iterated over. This is useful for printing out intermediate values in a long
  chain of range code, performing some operation with side-effects on each call
  tofrontorpopFront, or diverting the elements of a range into an
  auxiliaryOutputRange. | 
| 
									transposed(rr)
								 | Given a range of ranges, returns a range of ranges where the i'th subrange contains the i'th elements of the original subranges. | 
| 
									transversal(rr, n)
								 | Given a range of ranges, iterate transversally through the nth element of each of the enclosed ranges. This function
    is similar tounzipin other languages. | 
| 
									zip(ranges)
								 | Iterate several ranges in lockstep. The element type is a proxy tuple
   that allows accessing the current element in the nth range by
   usinge[n]. | 
Structs
| Name | Description | 
|---|---|
| 
									Chunks
								 | This range iterates over fixed-sized chunks of size chunkSizeof asourcerange.Sourcemust be an input range.chunkSizemust be greater than zero. | 
| 
									Cycle
								 | Repeats the given forward range ad infinitum. If the original range is
infinite (fact that would make Cyclethe identity application),Cycledetects that and aliases itself to the range type
itself. That works for non-forward ranges too.
If the original range has random access,Cycleoffers
random access and also offers a constructor taking an initial positionindex.Cycleworks with static arrays in addition to ranges,
mostly for performance reasons. | 
| 
									EvenChunks
								 | This range splits a sourcerange intochunkCountchunks of
approximately equal length.Sourcemust be a forward range with
known length. | 
| 
									FrontTransversal
								 | Given a range of ranges, iterate transversally through the first elements of each of the enclosed ranges. | 
| 
									Indexed
								 | This struct takes two ranges, sourceandindices, and creates a view
ofsourceas if its elements were reordered according toindices.indicesmay include only a subset of the elements ofsourceand
may also repeat elements. | 
| 
									Lockstep
								 | Iterate multiple ranges in lockstep using a foreachloop. In contrast tozipit allows reference access to its elements. If only a single
   range is passed in, theLockstepaliases itself away.  If the
   ranges are of different lengths ands==StoppingPolicystop after the shortest range is empty.  If the ranges are of different
   lengths ands==StoppingPolicy, throw an
   exception.smay not beStoppingPolicy, and passing this
   will throw an exception. | 
| 
									NullSink
								 | An OutputRange that discards the data it receives. | 
| 
									Recurrence
								 | Creates a mathematical sequence given the initial values and a
recurrence function that computes the next value from the existing
values. The sequence comes in the form of an infinite forward
range. The type Recurrenceitself is seldom used directly; most
often, recurrences are obtained by calling the functionrecurrence. | 
| 
									RefRange
								 | Wrapper which effectively makes it possible to pass a range by reference. Both the original range and the RefRange will always have the exact same elements. Any operation done on one will affect the other. So, for instance, if it's passed to a function which would implicitly copy the original range if it were passed to it, the original range is not copied but is consumed as if it were a reference type. | 
| 
									Repeat
								 | Create a range which repeats one value. | 
| 
									Sequence
								 | Sequenceis similar toRecurrenceexcept that iteration is
   presented in the so-called   closed form. This means that thenth element in the series is
   computable directly from the initial values andnitself. This
   implies that the interface offered bySequenceis a random-access
   range, as opposed to the regularRecurrence, which only offers
   forward iteration. | 
| 
									SortedRange
								 | Represents a sorted range. In addition to the regular range
primitives, supports additional operations that take advantage of the
ordering, such as merge and binary search. To obtain a SortedRangefrom an unsorted ranger, usesortwhich sortsrin place and returns the
correspondingSortedRange. To construct aSortedRangefrom a rangerthat is known to be already sorted, useassumeSorteddescribed
below. | 
| 
									Take
								 | Lazily takes only up to nelements of a range. This is
particularly useful when using with infinite ranges. | 
| 
									Transversal
								 | Given a range of ranges, iterate transversally through the nth element of each of the enclosed ranges. This function
    is similar tounzipin other languages. | 
| 
									Zip
								 | Iterate several ranges in lockstep. The element type is a proxy tuple
   that allows accessing the current element in the nth range by
   usinge[n]. | 
Enums
| Name | Description | 
|---|---|
| 
									SearchPolicy
								 | Policy used with the searching primitives lowerBound,   upperBound, andequalRangeofSortedRangebelow. | 
| 
									StoppingPolicy
								 | Dictates how iteration in a zipandlockstepshould stop.
   By default stop at the end of the shortest of all ranges. | 
| 
									TransverseOptions
								 | Options for the FrontTransversalandTransversalranges
   (below). | 
Manifest constants
| Name | Type | Description | 
|---|---|---|
| isTwoWayCompatible | Returns true if fnaccepts variables of type T1 and T2 in any order.
  The following code should compile: | 
Aliases
| Name | Type | Description | 
|---|---|---|
| Cycle | R | Repeats the given forward range ad infinitum. If the original range is
infinite (fact that would make Cyclethe identity application),Cycledetects that and aliases itself to the range type
itself. That works for non-forward ranges too.
If the original range has random access,Cycleoffers
random access and also offers a constructor taking an initial positionindex.Cycleworks with static arrays in addition to ranges,
mostly for performance reasons. | 
| SortedRange | SortedRange!(Unqual!(typeof(Range._input)),pred) | Represents a sorted range. In addition to the regular range
primitives, supports additional operations that take advantage of the
ordering, such as merge and binary search. To obtain a SortedRangefrom an unsorted ranger, usesortwhich sortsrin place and returns the
correspondingSortedRange. To construct aSortedRangefrom a rangerthat is known to be already sorted, useassumeSorteddescribed
below. | 
| Take | R | Lazily takes only up to nelements of a range. This is
particularly useful when using with infinite ranges. | 
Authors
Andrei Alexandrescu, David Simcha, Jonathan M Davis, and Jack Stouffer. Credit for some of the ideas in building this module goes to Leonardo Maffi.