Creating a higher-order range
Analogous to a higher-order function that is a function that returns a function, a higher-order range is a range that returns another range. This technique allows the lazy evaluation of results and maximum propagation of range features (for example, random access or bidirectionality) for best efficiency and type safety as you compose algorithms. Phobos' std.algorithm
module has several higher-order ranges. Here, we'll create a simplified version of std.algorithm.map
to explore the implementation and usage of this flexible concept.
How to do it…
Let's create a higher-order range by executing the following steps:
Make a
struct
template that stores another struct.Do your transformation in relevant places.
Forward all possible methods of the input range via
static if
.Create a helper method to create it conveniently.
Use a static assert to ensure it properly fulfils the interfaces.
Try using the interfaces!
The code is as follows:
import std.range; import std.traits; struct...