官术网_书友最值得收藏!

Introduction

This chapter goes into the details of an artefact central to the Phobos standard library with a little core language support: ranges. Ranges are user-defined objects used to build iterators over a collection of items. The collection may be pre-existing, such as an array, or it may be generated on the fly by the range object.

Ranges are defined in a way that they can be plugged together like building blocks with generic algorithms and other transformations. Command-line pipelines and range code can be very similar.

The Unix command-line command cat file.txt | sort | uniq can be expressed similarly in D, using ranges from std.stdio and std.algorithm and a helper function from std.range, as shown in the following code:

foreach(line; File("file.txt").byLine.map!(a=>a.idup).array.sort.uniq)
    writeln("Unique line: ", line);

Each range feeds into the next, building a system of generic building blocks that can be combined to perform a variety of tasks. In this chapter, we'll look at how to use ranges and how to create our own.

主站蜘蛛池模板: 肥乡县| 四川省| 舒城县| 虹口区| 鞍山市| 宁陕县| 石城县| 巴马| 长沙县| 吕梁市| 大渡口区| 海宁市| 敦煌市| 西华县| 台中市| 巫山县| 富顺县| 那曲县| 女性| 长子县| 天气| 灵武市| 大冶市| 汕头市| 普定县| 比如县| 深州市| 东乡| 江川县| 清新县| 修水县| 蓬莱市| 岱山县| 海安县| 西贡区| 遂平县| 临猗县| 靖州| 安多县| 晋江市| 青铜峡市|