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

  • D Cookbook
  • Adam D. Ruppe
  • 166字
  • 2021-07-16 11:50:47

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.

主站蜘蛛池模板: 恩平市| 青州市| 双峰县| 龙山县| 民丰县| 诏安县| 易门县| 鄯善县| 阿克陶县| 微山县| 平凉市| 东乌| 诏安县| 苍山县| 莱阳市| 桂阳县| 天水市| 财经| 康保县| 南宫市| 容城县| 江孜县| 凤冈县| 汽车| 六盘水市| 松桃| 永和县| 新源县| 宜都市| 光泽县| 宁安市| 灵武市| 修文县| 延寿县| 忻城县| 五大连池市| 郯城县| 西安市| 敦化市| 平利县| 兴和县|