Advent of Code 2023

Siarhei Siamashka siarhei.siamashka at gmail.com
Wed Dec 6 03:28:37 UTC 2023


On Sunday, 3 December 2023 at 18:56:32 UTC, Johannes Miesenhardt 
wrote:
> On Sunday, 3 December 2023 at 14:51:37 UTC, Siarhei Siamashka 
> wrote:
>> [...]
>
> Thanks, this is super helpful. I have one other question, in 
> the solution you posted and also the one I posted in the 
> discord today. I was required to use byLineCopy. I first used 
> byLine but I for some reason that I can't really explain only 
> got the last line from that. I switched to byLineCopy because I 
> saw it in other peoples solution and that magically fixed all 
> problems I had. What exactly happened here?

It's very important to know how slices and garbage collector work 
together in D language. In particular, the results produced by 
the following code may look surprising to beginners:

```D
import std;

void f1(ref int[] x) {
   x[0] += 1;
   x    ~= [9, 9, 9, 9, 9, 9];
   x[0] -= 1;
}

void f2(int[] x) {
   x[0] += 1;
   x    ~= [9, 9, 9, 9, 9, 9];
   x[0] -= 1;
}

void main() {
   int[] a = [1, 2, 3, 4];
   writefln!"original:       %s"(a); // [1, 2, 3, 4]
   f1(a);
   writefln!"after f1:       %s"(a); // [1, 2, 3, 4, 9, 9, 9, 9, 
9, 9]
   f2(a);
   writefln!"after f2:       %s"(a); // [2, 2, 3, 4, 9, 9, 9, 9, 
9, 9]
   f2(a);
   writefln!"after f2 again: %s"(a); // [3, 2, 3, 4, 9, 9, 9, 9, 
9, 9]
   a.reserve(100);
   writefln!"reserved extra capacity to allow doing resize 
in-place";
   f2(a);
   writefln!"after f2 again: %s"(a); // [3, 2, 3, 4, 9, 9, 9, 9, 
9, 9]
}

```

Coming from the other programming languages, people are usually 
familiar with the concept of passing function arguments either by 
value or by reference. And the behavior of the `f2` function may 
seem odd in the example above. It never changes the size of the 
original array, but may modify its data in unexpected ways 
contrary to naive expectations. There's a detailed article on 
this topic, where all the necessary answers can be found: 
https://dlang.org/articles/d-array-article.html

Many functions in D language have their pairs/siblings. The 
potentially wasteful `.byLineCopy` has its potentially 
destructive sibling `.byLine`. There are also 
`.split`/`.splitter` or `.retro`/`.reverse` pairs with their own 
subtle, but important differences. The beginners may prefer to 
start with the less efficient, but easier to use variants with no 
undesirable side effects.


More information about the Digitalmars-d-learn mailing list