Create an array with immutable elements

bearophile bearophileHUGS at lycos.com
Thu Jun 14 17:14:10 PDT 2012


Roman D. Boiko:

> immutable struct Node{ string s; }
> Node[] f()
> {
>   Node[] arr = ...?
>   return arr;
> }
>
> How to fill an array, if its elements are immutable? I want to 
> assign values calculated by some function.

In general sometimes it's not easy to build immutable data 
structures.

In D there are several ways to do something similar to what you 
ask, some alternatives (maybe there are more possibilities):

-------------------------------------

immutable struct Node { string s; }

string bar(in int x) pure nothrow
in {
     assert(x >= 0 && x <= 9);
} body {
     return "hello" ~ cast(char)(x + '0');
}

Node[] foo() {
     Node[] arr;
     enum size_t N = 5;
     arr.reserve(N);
     foreach (i; 0 .. N)
         arr ~= Node(bar(i));
     return arr;
}

void main() {
     import std.stdio;
     //writeln(foo()); // try this!
     writeln(foo()[0]);
}

-------------------------------------

import std.exception;

struct Node { string s; }

immutable(Node)[] foo() {
     enum size_t N = 5;
     auto arr = new Node[N];
     foreach (i; 0 .. N)
         arr[i] = Node("hello" ~ cast(char)(i + '0'));
     return assumeUnique(arr);
}

void main() {
     import std.stdio;
     writeln(foo()[0]);
}

-------------------------------------

struct Node { string s; }

immutable(Node)[] foo() pure nothrow {
     enum size_t N = 5;
     auto arr = new Node[N];
     foreach (i; 0 .. N)
         arr[i] = Node("hello" ~ cast(char)(i + '0'));
     return arr;
}

void main() {
     import std.stdio;
     writeln(foo()[0]);
}

-------------------------------------

struct Node { string s; }

Node[] foo() pure nothrow {
     enum size_t N = 5;
     auto arr = new Node[N];
     foreach (i; 0 .. N)
         arr[i] = Node("hello" ~ cast(char)(i + '0'));
     return arr;
}

void main() {
     import std.stdio;
     immutable result = foo();
     writeln(result[0]);
}

Bye,
bearophile



More information about the Digitalmars-d-learn mailing list