Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. Make a struct template that stores another struct.

  2. Do your transformation in relevant places.

  3. Forward all possible methods of the input range via static if.

  4. Create a helper method to create it conveniently.

  5. Use a static assert to ensure it properly fulfils the interfaces.

  6. Try using the interfaces!

The code is as follows:

import std.range;
import std.traits;
struct...