Creating immutable arrays in @safe code

Ali Çehreli acehreli at yahoo.com
Fri Jul 16 20:39:41 UTC 2021


On 7/16/21 1:19 PM, Dennis wrote:

 > I like passing around immutable data

I think the D community needs to talk more about guidelines around 
'immutable'. We don't... And I lack a complete understanding myself. :)

To me, 'immutable' is a demand of the user from the provider that the 
data will not mutate. So, I don't agree with the sentiment "I like 
passing around immutable data" because 'immutable' limits usability 
without a user to demand it to begin with. To me, 'immutable' must be 
used when really needed.

 > , but I don't like creating it.

I think making newly-created data 'immutable' renders it less useful. 
(The caller cannot mutate it.) So to me, newly created data should be 
mutable for the most usability. 'immutable' should be decided by the 
caller. Luckily, we have 'pure' allows the caller to make it 'immutable' 
effortlessly:

import std;

pure
int[] positive(int[] input) @safe
{
     return input.filter!(x => x > 0).array;
}

void main() {
   immutable p = positive([1, 2]);
}

Now the function is 'pure' and the caller's data is 'immutable' because 
the caller decided it had to be immutable. On the other hand, the 
function is happier because it is useful to callers that may mutate the 
data. :)

Ali



More information about the Digitalmars-d-learn mailing list