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

Putting a range interface on a collection


A range is a view into a collection. Ranges are typically mutable (though the individual elements may be immutable), so you can advance their position with popFront, but collections may be immutable. Here, we'll implement a stack data structure that exposes ranges to inspect it.

Getting ready

First, let's implement our stack type. A stack is a data type that fundamentally only needs two operations: push and pop. You push data on to the stack, and then pop data off in reverse order to which it was pushed. Popped data is removed from the stack. If we push 1 and then 2, we should pop 2 then 1. Popping from an empty stack is an error.

It is possible to use a built-in array directly as a stack, using slicing and the append operator (a ~ b), but this is woefully inefficient. Instead, we'll use a static buffer that can grow, if necessary, with a companion position variable. We can slice into a statically sized buffer to get started, and if this proves to be...