www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Higher Order Range Pattern

reply "Dennis Ritchie" <dennis.ritchie mail.ru> writes:
Hi,
I recently came across the following code:
http://wiki.dlang.org/Higher_Order_Range_Pattern


I can't understand why the properties and methods of the 
structure are called in the correct order.
Why are the property `back()` and the method `popBack()` are not 
called even once?
In general, please explain how it all works.

```
import std.stdio, std.range;

struct Retro(Range)
{
      property
     {
         auto ref front() { debug writeln("back"); return 
range_.back;  }
         auto ref back()  { debug writeln("front"); return 
range_.front; }
         bool empty()     { debug writeln("empty"); return 
range_.empty; }
     }

     void popFront() { debug writeln("popBack"); range_.popBack(); 
}
     void popBack()  { debug writeln("popFront"); 
range_.popFront(); }
	
     Range range_;
}

auto retro(Range)(Range range)
{
     return Retro!Range(range);
}

void main()
{
     import std.algorithm;
	
     auto arr = [1, 2, 3, 4, 5];
     assert(equal(retro(arr), [5, 4, 3, 2, 1]));
}
```
http://rextester.com/FMPGS76502
Jun 22 2015
parent reply Steven Schveighoffer <schveiguy yahoo.com> writes:
On 6/22/15 11:04 AM, Dennis Ritchie wrote:
 Hi,
 I recently came across the following code:
 http://wiki.dlang.org/Higher_Order_Range_Pattern


 I can't understand why the properties and methods of the structure are
 called in the correct order.
 Why are the property `back()` and the method `popBack()` are not called
 even once?
Because std.algorithm.equal does not use back or popBack.
 In general, please explain how it all works.
I have a feeling you are not understanding something. This code is pretty straightforward, I don't know what else to explain about it. -Steve
Jun 22 2015
parent "Dennis Ritchie" <dennis.ritchie mail.ru> writes:
On Monday, 22 June 2015 at 15:25:12 UTC, Steven Schveighoffer 
wrote:
 On 6/22/15 11:04 AM, Dennis Ritchie wrote:
 Hi,
 I recently came across the following code:
 http://wiki.dlang.org/Higher_Order_Range_Pattern


 I can't understand why the properties and methods of the 
 structure are
 called in the correct order.
 Why are the property `back()` and the method `popBack()` are 
 not called
 even once?
Because std.algorithm.equal does not use back or popBack.
 In general, please explain how it all works.
I have a feeling you are not understanding something. This code is pretty straightforward, I don't know what else to explain about it. -Steve
Thanks. I understand everything, just std.algorithm.equal introduced me to the great confusion :) Now everything fell into place.
Jun 22 2015