"chain" vs "~"

Emanuele Torre torreemanuele6 at gmail.com
Sun Aug 7 03:55:50 UTC 2022


On Sunday, 7 August 2022 at 01:22:18 UTC, 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;
> '''

They are quite different:
* `chain` gives you "range" (iterator) that starts from the first 
element of `x` and ends at the last element of `y` (like e.g. 
`zip` in other languages).
* `~` creates a new `int[]` with elements from `x` and the 
elements from `y`.

If you use `z[2] = 10;`, you will change `x[2]` as well, since 
`z` is just an iterator of which the third element is the value 
stored in `x[2]`; if you use `z[4] = 11;`, you will change 
`y[1]`; if you change `y[0]`, `z[3]` will also change; etc. (n.b. 
if you replace `x` and `y` with other arrays, then this doesn't 
apply because then `x` and `y` use different memory.)

`z` is just a range you can use to access the memory of those 
`[1,2,3]` and `[4,5,6]` arrays, not a new array.

Here is some example code to show the differences:

```D
void main()
{
     import std.range : chain;
     import std.stdio : writefln;

     int[] x = [ 1, 2, 3 ];
     int[] y = [ 4, 5, 6 ];

     auto z = chain(x, y);
     auto j = x ~ y;

     writefln("x: %(%s %)", x);
     writefln("y: %(%s %)", y);
     writefln("z: %(%s %)", z);
     writefln("j: %(%s %)", j);

     writefln("----y[1]=10;---");
     y[1] = 10;

     writefln("x: %(%s %)", x);
     writefln("y: %(%s %)", y);
     writefln("z: %(%s %)", z);
     writefln("j: %(%s %)", j);

     writefln("----z[2]=9;----");
     z[2] = 9;

     writefln("x: %(%s %)", x);
     writefln("y: %(%s %)", y);
     writefln("z: %(%s %)", z);
     writefln("j: %(%s %)", j);

     writefln("----j[2]=8;----");
     j[2] = 8;

     writefln("x: %(%s %)", x);
     writefln("y: %(%s %)", y);
     writefln("z: %(%s %)", z);
     writefln("j: %(%s %)", j);
}
```

output:
```
x: 1 2 3
y: 4 5 6
z: 1 2 3 4 5 6
j: 1 2 3 4 5 6
----y[1]=10;---
x: 1 2 3
y: 4 10 6
z: 1 2 3 4 10 6
j: 1 2 3 4 5 6
----z[2]=9;----
x: 1 2 9
y: 4 10 6
z: 1 2 9 4 10 6
j: 1 2 3 4 5 6
----j[2]=8;----
x: 1 2 9
y: 4 10 6
z: 1 2 9 4 10 6
j: 1 2 8 4 5 6
```



More information about the Digitalmars-d-learn mailing list