bringToFront() and arrays of char

Ali Çehreli acehreli at yahoo.com
Wed Dec 12 17:34:53 PST 2012


On 12/12/2012 05:18 PM, Mu wrote:
 > Why doesn't the below code compile?
 > How to rewrite it so that it does?
 > Using: DMD64 D Compiler v2.060.
 > Thank you.
 >
 > Code:
 > ----------------
 >
 > import std.algorithm, std.ascii, std.stdio;
 >
 > void main()
 > {
 > char[] rot13 = lowercase.dup;
 >
 > bringToFront(rot13[0 .. 13], rot13[13 .. $]);
 > writeln(rot13);
 > }
 >
 > ----------------
 >
 > Errors:
 >
 > /usr/include/dmd/phobos/std/algorithm.d(1762): Error: front(r1)
 > is not an lvalue

This is a common pitfall of using char[] with range functions. Range 
functions like bringToFront() use the .front property. .front 
unintuitively returns dchar for a char[] range. That dchar is decoded 
from the UTF-8 code units of the char[].

You can use std.conv.to:

import std.algorithm, std.ascii, std.stdio;
import std.conv;

void main()
{
     dchar[] rot13 = lowercase.to!(dchar[]);

     bringToFront(rot13[0 .. 13], rot13[13 .. $]);
     writeln(rot13);
}

By dtext:

     dchar[] rot13 = lowercase.dtext.dup;

If you are dealing with ASCII, you may want to use ubyte instead. The 
following is one way of achieving that:

import std.array;
// ...
     ubyte[] rot13 = lowercase.map!(a => cast(ubyte)a).array;

(There must be an easier way of doing that. :))

Ali



More information about the Digitalmars-d-learn mailing list