"chain" vs "~"

Ali Çehreli acehreli at yahoo.com
Mon Aug 8 18:49:26 UTC 2022


On 8/6/22 18:22, pascal111 wrote:
 > Why we use "chain" while we have "~":
 >
 > '''D
 > int[] x=[1,2,3];
 > int[] y=[4,5,6];
 >
 > auto z=chain(x,y);
 > auto j=x~y;
 > '''

To add to what has already mentioned,

- chain can be used on ranges that are of different element types

- as usual, some of the ranges may be generators

- although obscure, one may sort in-place over multiple ranges (requires 
RandomAccessRange.)

This program shows the first two points:

import std; // Apologies for terseness

void main() {
   auto ints = [ 10, 3, 7 ];
   auto squares = iota(10).map!squared.take(5);
   auto doubles = [ 1.5, -2.5 ];
   auto c = chain(ints, squares, doubles);

   // Different types but CommonType is 'double' here:
   static assert(is(ElementType!(typeof(c)) == double));

   // Prints [10, 3, 7, 0, 1, 4, 9, 16, 1.5, -2.5]
   writeln(c);
}

auto squared(T)(T value) {
   return value * value;
}

And this one shows how one can sort in-place multiple arrays:

import std; // Ditto

void main() {
   auto a = [ 10, 3, 7 ];
   auto b = [ 15, -25 ];

   auto c = chain(a, b);
   sort(c);

   writeln(a);  // Prints [-25, 3, 7]
   writeln(b);  // Prints [10, 15]
}

Ali



More information about the Digitalmars-d-learn mailing list