Associative array printing problems

KennyTM~ kennytm at gmail.com
Wed Jun 22 12:02:37 PDT 2011


On Jun 23, 11 02:45, bearophile wrote:
> Printing associative arrays in a decent way is not a luxury, it's a basic skill I expect D writeln to have.
>
> This is reduced from a program related to the coding Kata Nineteen, Word Chains. The problem asks to create the longest chain of words. This function creates an associative array where the keys are the start chars of words, and the values are sets of words. For simplicity in D2 I have implemented the string sets as bool[string].
>
>
> import std.stdio, std.string;
>
> bool[string][char] foo(string[] names) {
>      typeof(return) result;
>      foreach (name; names)
>          result[name[0]][name] = true;
>      return result;
> }
>
> auto names = "mary patricia linda barbara elizabeth jennifer
>      maria susan margaret dorothy lisa nancy karen betty helen
>      sandra donna carol ruth sharon michelle laura sarah
>      kimberly deborah jessica shirley cynthia angela melissa
>      brenda amy anna rebecca virginia kathleen pamela";
>
> void main() {
>      writeln(foo(names.split()));
> }
>
>
> The original complete program didn't have to print this result, but there I have created a bug, so I have had to print result, as I have done in this reduced program. This is the printout:
>
>
> p:patricia:true pamela:true l:linda:true lisa:true laura:true d:dorothy:true donna:true deborah:true h:helen:true m:melissa:true margaret:true michelle:true maria:true mary:true e:elizabeth:true a:angela:true anna:true amy:true b:barbara:true betty:true brenda:true j:jessica:true jennifer:true n:nancy:true r:ruth:true rebecca:true v:virginia:true s:sharon:true susan:true shirley:true sandra:true sarah:true k:kathleen:true karen:true kimberly:true c:cynthia:true carol:true
>
>
[snip]
>
> Bye,
> bearophile

Workaround:

     writeln(to!string(foo(names.split())));

this gives

[p:[patricia:true, pamela:true], l:[linda:true, lisa:true, laura:true], 
d:[dorothy:true, donna:true, deborah:true], h:[helen:true], 
m:[melissa:true, margaret:true, michelle:true, maria:true, mary:true], 
e:[elizabeth:true], a:[angela:true, anna:true, amy:true], 
b:[barbara:true, betty:true, brenda:true], j:[jessica:true, 
jennifer:true], n:[nancy:true], r:[ruth:true, rebecca:true], 
v:[virginia:true], s:[sharon:true, susan:true, shirley:true, 
sandra:true, sarah:true], k:[kathleen:true, karen:true, kimberly:true], 
c:[cynthia:true, carol:true]]

Not the same as what you expect, but at least it's readable enough. But 
a big problem is std.stdio.writeln, std.format.formattedWrite, 
std.conv.to all use different mechanism to write a string, as 
illustrated in:

   import std.stdio, std.string, std.conv;
   void main() {
     int[int] x = [5:6,7:8];
     writeln(x);
     writeln(format("%s", x));
     writeln(to!string(x));
   }

output:

5:6 7:8
[5:6,7:8]
[5:6, 7:8]



More information about the Digitalmars-d mailing list