The OpenD Programming Language

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.algorithm) to be used with a vast variety of different concrete types. For example, a linear search algorithm such as std.algorithm.searching.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:

Submodules:

This module has two submodules:

The std.range.primitives 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.range.interfaces 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:

More...

Modules

interfaces
module std.range.interfaces

This module is a submodule of std.range.

primitives
module std.range.primitives

This module is a submodule of std.range.

Public Imports

std.array
public import std.array;
Undocumented in source.
std.range.interfaces
public import std.range.interfaces;
Undocumented in source.
std.range.primitives
public import std.range.primitives;
Undocumented in source.

Members

Enums

SearchPolicy
enum SearchPolicy

Policy used with the searching primitives lowerBound, upperBound, and equalRange of SortedRange below.

SortedRangeOptions
enum SortedRangeOptions

Options for SortedRange ranges (below).

StoppingPolicy
enum StoppingPolicy

Dictates how iteration in a zip and lockstep should stop. By default stop at the end of the shortest of all ranges.

TransverseOptions
enum TransverseOptions

Options for the FrontTransversal and Transversal ranges (below).

Functions

assumeSorted
auto assumeSorted(R r)

Assumes r is sorted by predicate pred and returns the corresponding SortedRange!(pred, R) having r as support. To check for sorted-ness at cost O(n), use std.algorithm.sorting.isSorted.

bitwise
auto bitwise(R 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
auto chain(Ranges rs)

Spans multiple ranges in sequence. The function chain takes any number of ranges and returns a Chain!(R1, R2,...) object. The ranges may be different, but they must have the same element type. The result is a range that offers the front, popFront, and empty primitives. If all input ranges offer random access and length, Chain offers them as well.

choose
auto choose(bool condition, R1 r1, R2 r2)

Choose one of two ranges at runtime depending on a Boolean condition.

chooseAmong
auto chooseAmong(size_t index, Ranges rs)

Choose one of multiple ranges at runtime.

chunks
Chunks!Source chunks(Source source, size_t chunkSize)

This range iterates over fixed-sized chunks of size chunkSize of a source range. Source must be an input range. chunkSize must be greater than zero.

cycle
auto cycle(R input)
Cycle!R cycle(R input, size_t index)

Repeats the given forward range ad infinitum. If the original range is infinite (fact that would make Cycle the identity application), Cycle detects that and aliases itself to the range type itself. That works for non-forward ranges too. If the original range has random access, Cycle offers random access and also offers a constructor taking an initial position index. Cycle works with static arrays in addition to ranges, mostly for performance reasons.

drop
R drop(R range, size_t n)
dropBack
R dropBack(R range, size_t n)

Convenience function which calls std.range.primitives.popFrontN(range, n) and returns range. drop makes it easier to pop elements from a range and then pass it to another function within a single expression, whereas popFrontN would require multiple statements.

dropBackExactly
R dropBackExactly(R range, size_t n)

Similar to drop and dropBack but they call range.$(LREF popFrontExactly)(n) and range.popBackExactly(n) instead.

dropBackOne
R dropBackOne(R range)

Convenience function which calls range.popFront() and returns range. dropOne makes it easier to pop an element from a range and then pass it to another function within a single expression, whereas popFront would require multiple statements.

dropExactly
R dropExactly(R range, size_t n)

Similar to drop and dropBack but they call range.$(LREF popFrontExactly)(n) and range.popBackExactly(n) instead.

dropOne
R dropOne(R range)

Convenience function which calls range.popFront() and returns range. dropOne makes it easier to pop an element from a range and then pass it to another function within a single expression, whereas popFront would require multiple statements.

enumerate
auto enumerate(Range range, Enumerator start)

Iterate over range with an attached index variable.

evenChunks
EvenChunks!Source evenChunks(Source source, size_t chunkCount)

This range splits a source range into chunkCount chunks of approximately equal length. Source must be a forward range with known length.

frontTransversal
FrontTransversal!(RangeOfRanges, opt) frontTransversal(RangeOfRanges rr)

Given a range of ranges, iterate transversally through the first elements of each of the enclosed ranges.

generate
auto generate(Fun fun)
auto generate()

Given callable (std.traits.isCallable) fun, create as a range whose front is defined by successive calls to fun(). 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 entire front/popFront/empty structure. fun maybe be passed either a template alias parameter (existing function, delegate, struct type defining static opCall) or a run-time value argument (delegate, function object). The result range models an InputRange (std.range.primitives.isInputRange). The resulting range will call fun() on construction, and every call to popFront, and the cached value will be returned when front is called.

indexed
Indexed!(Source, Indices) indexed(Source source, Indices indices)

This struct takes two ranges, source and indices, and creates a view of source as if its elements were reordered according to indices. indices may include only a subset of the elements of source and may also repeat elements.

iota
auto iota(B begin, E end, S step)
auto iota(B begin, E end)
auto iota(E end)

Creates a range of values that span the given starting and stopping values.

lockstep
Lockstep!(Ranges) lockstep(Ranges ranges)
Lockstep!(Ranges) lockstep(Ranges ranges, StoppingPolicy s)

Iterate multiple ranges in lockstep using a foreach loop. In contrast to zip it allows reference access to its elements. If only a single range is passed in, the Lockstep aliases itself away. If the ranges are of different lengths and s == StoppingPolicy.shortest stop after the shortest range is empty. If the ranges are of different lengths and s == StoppingPolicy.requireSameLength, throw an exception. s may not be StoppingPolicy.longest, and passing this will throw an exception.

nullSink
auto ref nullSink()

An OutputRange that discards the data it receives.

only
auto only(Values values)
auto only()

Assemble values into a range that carries all its elements in-situ.

padLeft
auto padLeft(R r, E e, size_t n)

Extends the length of the input range r by padding out the start of the range with the element e. The element e must be of a common type with the element type of the range r as defined by std.traits.CommonType. If n is less than the length of of r, then r is returned unmodified.

padRight
auto padRight(R r, E e, size_t n)

Extend the length of the input range r by padding out the end of the range with the element e. The element e must be of a common type with the element type of the range r as defined by std.traits.CommonType. If n is less than the length of of r, then the contents of r are returned.

radial
auto radial(Range r, I startingIndex)
auto radial(R r)

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.

rebindable (from std.typecons)
Rebindable!T rebindable(Rebindable!T obj) via public import std.typecons : Flag, Yes, No, Rebindable, rebindable;

This function simply returns the Rebindable object passed in. It's useful in generic programming cases when a given object may be either a regular class or a Rebindable.

recurrence
Recurrence!(fun, CommonType!(State), State.length) recurrence(State 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 Recurrence itself is seldom used directly; most often, recurrences are obtained by calling the function recurrence.

refRange
auto refRange(R* 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
Repeat!T repeat(T value)
Take!(Repeat!T) repeat(T value, size_t n)

Create a range which repeats one value.

retro
auto retro(Range r)

Iterates a bidirectional range backwards. The original range can be accessed by using the source property. Applying retro twice to the same range yields the original range.

roundRobin
auto roundRobin(Rs rs)

roundRobin(r1, r2, r3) yields r1.front, then r2.front, then r3.front, after which it pops off one element from each and continues again from r1. For example, if two ranges are involved, it alternately yields elements off the two ranges. roundRobin stops after it has consumed all ranges (skipping over the ones that finish early).

sequence
auto sequence(State args)

Sequence is similar to Recurrence except that iteration is presented in the so-called closed form. This means that the nth element in the series is computable directly from the initial values and n itself. This implies that the interface offered by Sequence is a random-access range, as opposed to the regular Recurrence, which only offers forward iteration.

slide
auto slide(Source source, size_t windowSize, size_t stepSize)

A fixed-sized sliding window iteration of size windowSize over a source range by a custom stepSize.

stride
auto stride(Range r, size_t n)

Iterates range r with stride n. If the range is a random-access range, moves by indexing into the range; otherwise, moves by successive calls to popFront. 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 for n to be 0.

tail
auto tail(Range range, size_t n)

Return a range advanced to within _n elements of the end of range.

take
Take!R take(R input, size_t n)

Lazily takes only up to n elements of a range. This is particularly useful when using with infinite ranges.

takeExactly
auto takeExactly(R range, size_t n)

Similar to take, but assumes that range has at least n elements. Consequently, the result of takeExactly(range, n) always defines the length property (and initializes it to n) even when range itself does not define length.

takeNone
auto takeNone()

Returns an empty range which is statically known to be empty and is guaranteed to have length and be random access regardless of R's capabilities.

takeNone
auto takeNone(R range)

Creates an empty range from the given range in O(1). If it can, it will return the same range type. If not, it will return takeExactly(range, 0).

takeOne
auto takeOne(R source)

Returns a range with at most one element; for example, takeOne([42, 43, 44]) returns a range consisting of the integer 42. Calling popFront() off that range renders it empty.

tee
auto tee(R1 inputRange, R2 outputRange)
auto tee(R1 inputRange)

Implements a "tee" style pipe, wrapping an input range so that elements of the range can be passed to a provided function or OutputRange as 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 to front or popFront, or diverting the elements of a range into an auxiliary OutputRange.

transposed
Transposed!(RangeOfRanges, opt) transposed(RangeOfRanges 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
Transversal!(RangeOfRanges, opt) transversal(RangeOfRanges rr, size_t n)

Given a range of ranges, iterate transversally through the nth element of each of the enclosed ranges. This function is similar to unzip in other languages.

zip
auto zip(Ranges ranges)
auto zip(StoppingPolicy sp, Ranges ranges)

Iterate several ranges in lockstep. The element type is a proxy tuple that allows accessing the current element in the nth range by using e[n].

Structs

Chunks
struct Chunks(Source)

This range iterates over fixed-sized chunks of size chunkSize of a source range. Source must be an input range. chunkSize must be greater than zero.

Cycle
struct Cycle(R)

Repeats the given forward range ad infinitum. If the original range is infinite (fact that would make Cycle the identity application), Cycle detects that and aliases itself to the range type itself. That works for non-forward ranges too. If the original range has random access, Cycle offers random access and also offers a constructor taking an initial position index. Cycle works with static arrays in addition to ranges, mostly for performance reasons.

EvenChunks
struct EvenChunks(Source)

This range splits a source range into chunkCount chunks of approximately equal length. Source must be a forward range with known length.

FrontTransversal
struct FrontTransversal(Ror, TransverseOptions opt = TransverseOptions.assumeJagged)

Given a range of ranges, iterate transversally through the first elements of each of the enclosed ranges.

Indexed
struct Indexed(Source, Indices)

This struct takes two ranges, source and indices, and creates a view of source as if its elements were reordered according to indices. indices may include only a subset of the elements of source and may also repeat elements.

Lockstep
struct Lockstep(Ranges...)

Iterate multiple ranges in lockstep using a foreach loop. In contrast to zip it allows reference access to its elements. If only a single range is passed in, the Lockstep aliases itself away. If the ranges are of different lengths and s == StoppingPolicy.shortest stop after the shortest range is empty. If the ranges are of different lengths and s == StoppingPolicy.requireSameLength, throw an exception. s may not be StoppingPolicy.longest, and passing this will throw an exception.

No (from std.typecons)
struct No via public import std.typecons : Flag, Yes, No, Rebindable, rebindable;

Convenience names that allow using e.g. Yes.encryption instead of Flag!"encryption".yes and No.encryption instead of Flag!"encryption".no.

NullSink
struct NullSink

An OutputRange that discards the data it receives.

Rebindable (from std.typecons)
struct Rebindable(T) via public import std.typecons : Flag, Yes, No, Rebindable, rebindable;

Rebindable!(T) is a simple, efficient wrapper that behaves just like an object of type T, except that you can reassign it to refer to another object. For completeness, Rebindable!(T) aliases itself away to T if T is a non-const object type.

Recurrence
struct Recurrence(alias fun, StateType, size_t stateSize)

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 Recurrence itself is seldom used directly; most often, recurrences are obtained by calling the function recurrence.

RefRange
struct RefRange(R)

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
struct Repeat(T)

Create a range which repeats one value.

Sequence
struct Sequence(alias fun, State)

Sequence is similar to Recurrence except that iteration is presented in the so-called closed form. This means that the nth element in the series is computable directly from the initial values and n itself. This implies that the interface offered by Sequence is a random-access range, as opposed to the regular Recurrence, which only offers forward iteration.

SortedRange
struct SortedRange(Range, alias pred = "a < b", SortedRangeOptions opt = SortedRangeOptions.assumeSorted)

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 SortedRange from an unsorted range r, use std.algorithm.sorting.sort which sorts r in place and returns the corresponding SortedRange. To construct a SortedRange from a range r that is known to be already sorted, use assumeSorted.

Take
struct Take(Range)

Lazily takes only up to n elements of a range. This is particularly useful when using with infinite ranges.

Transversal
struct Transversal(Ror, TransverseOptions opt = TransverseOptions.assumeJagged)

Given a range of ranges, iterate transversally through the nth element of each of the enclosed ranges. This function is similar to unzip in other languages.

Yes (from std.typecons)
struct Yes via public import std.typecons : Flag, Yes, No, Rebindable, rebindable;

Convenience names that allow using e.g. Yes.encryption instead of Flag!"encryption".yes and No.encryption instead of Flag!"encryption".no.

Zip
struct 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 using e[n].

Templates

Cycle
template Cycle(R)

Repeats the given forward range ad infinitum. If the original range is infinite (fact that would make Cycle the identity application), Cycle detects that and aliases itself to the range type itself. That works for non-forward ranges too. If the original range has random access, Cycle offers random access and also offers a constructor taking an initial position index. Cycle works with static arrays in addition to ranges, mostly for performance reasons.

Flag (from std.typecons)
template Flag(string name) via public import std.typecons : Flag, Yes, No, Rebindable, rebindable;

Defines a simple, self-documenting yes/no flag. This makes it easy for APIs to define functions accepting flags without resorting to bool, which is opaque in calls, and without needing to define an enumerated type separately. Using Flag!"Name" instead of bool makes the flag's meaning visible in calls. Each yes/no flag has its own type, which makes confusions and mix-ups impossible.

SortedRange
template SortedRange(Range, alias pred = "a < b", SortedRangeOptions opt = SortedRangeOptions.assumeSorted)

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 SortedRange from an unsorted range r, use std.algorithm.sorting.sort which sorts r in place and returns the corresponding SortedRange. To construct a SortedRange from a range r that is known to be already sorted, use assumeSorted.

Take
template Take(R)

Lazily takes only up to n elements of a range. This is particularly useful when using with infinite ranges.

isSomeFiniteCharInputRange
template isSomeFiniteCharInputRange(R)

This simplifies a commonly used idiom in phobos for accepting any kind of string parameter. The type R can for example be a simple string, chained string using std.range.chain, std.path.chainPath or any other input range of characters.

isTwoWayCompatible
template isTwoWayCompatible(alias fn, T1, T2)

Returns true if fn accepts variables of type T1 and T2 in any order. The following code should compile:

Detailed Description

chainConcatenates several ranges into a single range.
chooseChooses one of two ranges at runtime based on a boolean condition.
chooseAmongChooses one of several ranges at runtime based on an index.
chunksCreates a range that returns fixed-size chunks of the original range.
cycleCreates an infinite range that repeats the given forward range indefinitely. Good for implementing circular buffers.
dropCreates the range that results from discarding the first n elements from the given range.
dropBackCreates the range that results from discarding the last n elements from the given range.
dropExactlyCreates the range that results from discarding exactly n of the first elements from the given range.
dropBackExactlyCreates the range that results from discarding exactly n of the last elements from the given range.
dropOneCreates the range that results from discarding the first element from the given range.
$(LREF dropBackOne)Creates the range that results from discarding the last element from the given range.
enumerateIterates a range with an attached index variable.
evenChunksCreates a range that returns a number of chunks of approximately equal length from the original range.
frontTransversalCreates a range that iterates over the first elements of the given ranges.
generateCreates a range by successive calls to a given function. This allows to create ranges as a single delegate.
indexedCreates a range that offers a view of a given range as though its elements were reordered according to a given range of indices.
iotaCreates a range consisting of numbers between a starting point and ending point, spaced apart by a given interval.
lockstepIterates n ranges in lockstep, for use in a foreach loop. Similar to zip, except that lockstep is designed especially for foreach loops.
nullSinkAn output range that discards the data it receives.
onlyCreates a range that iterates over the given arguments.
padLeftPads 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.
padRightLazily pads a range to a specified length by adding a given element to the back of the range.
radialGiven 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.
recurrenceCreates a forward range whose values are defined by a mathematical recurrence relation.
refRangePass 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.
repeatCreates a range that consists of a single element repeated n times, or an infinite range repeating that element indefinitely.
retroIterates a bidirectional range backwards.
roundRobinGiven 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.
sequenceSimilar to recurrence, except that a random-access range is created.
$(LREF slide)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.
strideIterates a range with stride n.
tailReturn a range advanced to within n elements of the end of the given range.
takeCreates a sub-range consisting of only up to the first n elements of the given range.
takeExactlyLike take, but assumes the given range actually has n elements, and therefore also defines the length property.
takeNoneCreates a random-access range consisting of zero elements of the given range.
takeOneCreates a random-access range consisting of exactly the first element of the given range.
teeCreates a range that wraps a given range, forwarding along its elements while also calling a provided function with each element.
transposedTransposes a range of ranges.
transversalCreates a range that iterates over the n'th elements of the given random-access ranges.
zipGiven 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 std.algorithm.sorting.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.

Meta

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.