Linked list, printing looks destructive.

Ali Çehreli acehreli at yahoo.com
Mon Apr 25 02:19:46 UTC 2022


On 4/24/22 18:40, Alain De Vod wrote:

 > I think this has something to do with popFront

This type violates a fundamental rule: Containers and ranges are 
separate concepts. Your List is a container, not a range. I changed your 
code by moving the range functions to a Range struct that is created by 
opSlice():

class List {
     Node * root=null;
     this(int[] AR){foreach(i ; AR)pushfront(i);}

     auto opSlice() {
       return Range(root);
     }

     static struct Range {
       Node * root_;

       bool empty() const {return !root_;}
       void popFront() {root_=root_.next;}
       float front() const {return root_.element;}
     }

     void pushfront(int element) {
       Node * newnode=new Node();
       newnode.element=element;
       newnode.next=root;
       root=newnode;
     }
}//List

The foreach loop implicitly calls opSlice() and it all works.[1] When 
you want a range, you can call opSlice indirectly by using [] after the 
object:

     import std.algorithm;
     writeln(l[].map!(e => e * 2));

Ali

[1] As reported recently by Steven Schveighoffer, this information is 
missing in my book: 
https://bitbucket.org/acehreli/ddili/issues/33/add-additional-foreach-mechanism-to-range



More information about the Digitalmars-d-learn mailing list