Functional Programming with D
Chris Cain
clcain at uncg.edu
Sat Apr 13 21:08:52 PDT 2013
On Sunday, 14 April 2013 at 00:38:24 UTC, Ali Çehreli wrote:
> 3) "D does not allow you to cast something to immutable"
>
> I think you mean "no implicit conversion" because it is not
> true if we take what you said literally:
>
> auto a = [ 1, 2 ];
> immutable i = cast(immutable)a; // dangerous
>
> a[0] = 42;
> assert(i[0] == 42); // oops: immutable element has changed!
>
> Ali
Also, the usual way to do this (if you're doing it _properly_,
this is still vulnerable to being misused) is using
`assumeUnique` ... the "requirements" for that function are
implied by its name: it really wants a unique reference that will
be transformed into an immutable.
```
import std.exception : assumeUnique;
static immutable size_t base = cast(size_t) ('z' - 'a') + 1;
// Remember:
// alias string = immutable(char)[]
string numToString(size_t length, size_t num) {
char[] result = new char[](length);
foreach_reverse(ref e; result) {
auto digit = num % base;
e = cast(char)('a' + digit);
num /= base;
}
// OK because no other references exist
return assumeUnique(result);
}
```
More information about the Digitalmars-d-announce
mailing list