Creating immutable arrays in @safe code

Dennis dkorpel at gmail.com
Fri Jul 16 22:21:28 UTC 2021


On Friday, 16 July 2021 at 20:39:41 UTC, Ali Çehreli wrote:
> So to me, newly created data should be mutable for the most 
> usability.

It's clear that I stripped away too much context with the toy 
examples, so let me try to add some back. I don't like forcing 
the use of `immutable` in general, but it's useful for 
transforming reference types into value types (inspired by 
[invariant 
strings](https://www.digitalmars.com/articles/b01.html) and 
`std.bigint`). The actual data structure I'm working with is a 
tree that looks like:

```D
struct Expression
{
     immutable(Expression)[] children;
     int value;
}
```

> Now the function is 'pure' and the caller's data is 'immutable' 
> because the caller decided it had to be immutable.

I've encountered the use of `pure` for creating immutable data 
before, e.g: [Function Purity and Immutable Data Structure 
Construction](https://www.digitalmars.com/articles/b92.html). But 
`pure` is no silver bullet:

```D
import std;

pure: @safe:

struct Expression
{
     immutable(Expression)[] children;
     int value;
}

Expression withSortedChildren(Expression exp)
{
     return Expression(expr.children.dup.sort!((a, b) => a.value < 
b.value).release);
}
```

> Error: cannot implicitly convert expression 
> `sort(dup(cast(const(Expression)[])expr.children)).release()` 
> of type `Expression[]` to `immutable(Expression)[]`

I've tried structuring it in a way that makes the compiler allow 
the conversion to immutable, but had no luck so far.



More information about the Digitalmars-d-learn mailing list