Is there such concept of a list in D?

Salih Dincer salihdb at hotmail.com
Sat Dec 10 19:49:23 UTC 2022


On Saturday, 10 December 2022 at 05:46:26 UTC, thebluepandabear 
wrote:
> In most languages there is some sort of `List<T>` type, is that 
> the same for D?

The standard library has many possibilities, including linked 
lists. What about the news from the range...

In D, the concept of range is very advanced. Now I'm going to 
show you 3 examples and two of them are from the standard library 
and the other is a nice wrap:

```d
struct List(A) {
   A[] *arr;

   auto put(R)(R value) { (*arr) ~= value; }
   auto length() { return (*arr).length; }

   auto empty() {
     import std.range : empty;
     return (*arr).empty;
   }

   auto front() {
     import std.range : item = front;//back;
     return (*arr).item;
   }

   void popFront() {
     import std.range : next = popFront;//popBack
     (*arr).next;
   }
}

auto listHelper(A)(return ref A[] arr) {
   return List!A(&arr);
}

alias immutable(char[]) [] strings;

void main() {
   strings myNames = ["El-Mevla", "Hodja", "Nasreddin",
                      "Sivrihisar", "Shemseddin",
                      "Nasruddin", "Nusrat"];
   strings list;
   auto myList1 = listHelper(list);

   import std.range;
   auto myList2 = appender!strings;

   import std.container.array;
   auto myList3 = Array!string();

   foreach(name; myNames)
   {
     myList1.put(name);
     myList2.put(name);
     myList3.insert(name);
   }

   void rangePrint(R)(R range)
   {
     import std.stdio;
     size_t i = 1;
     foreach(item; range)
     {
       writeln(i++, ": ", item);
     }
     writeln;
   }

   rangePrint(myList1);
   rangePrint(myList2);
   rangePrint(myList3);
}
```

SDB at 79


More information about the Digitalmars-d-learn mailing list