www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Error: no property 'sort' for type 'ulong[string]' , sometimes

reply "Derix" <derix dexample.com> writes:
Hi there,

So I've just stated learning D. Playing with associative arrays,
I wrote this simple function. No big deal.

void associativeArrayFu(){
	ulong[string] arr;
	arr["foo"]=1;
	arr["bar"]=2;
	arr["foo"]=45;
	
	foreach( thing;arr.sort){
		writeln( thing );
		}
	}

Compiles and runs just fine.
Stating to have a bunch of funtions in one file, I reorganised my
sources among several files (in the same project in Eclipse).

Now the same function yelds this error when compiling:

Error: no property 'sort' for type 'ulong[string]'

wether it is in a source file alongside other functions, alone in
its own file, or even all alone in its own project.

Not that I care that much about this poor function, but I am
puzzled. What did I miss ?
Oct 20 2013
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Derix:

What did I miss ?

Never use the built-in ".sort" property, it's deprecated, buggy 
and slow. It's still in the language for unknown reasons, perhaps 
to create nice traps for language newcomers.

Also, what do you mean sorting an associative array? To sort the 
keys (notice the name with two leading "a" and the trailing () to 
call the Phobos sort function of std.algorithm that you have to 
import):

auto sortedKeys = aarr.byKey.array.sort().release;
auto sortedValues = aarr.byValua.array.sort().release;

Bye,
bearophile
Oct 20 2013
parent "Derix" <derix dexample.com> writes:
On Sunday, 20 October 2013 at 16:06:54 UTC, bearophile wrote:
 Also, what do you mean sorting an associative array?
Yep, that's the point. I fumbled further and came to the realization that maybe there is no such thing as a sorted associative array. That would have be something that, when you foreach on it, the keys (which in fact hold the valuable material) come in order, such as in assarr("alice")=12 assarr("bob")=0 assarr("charlie")=7 but I guess that's not really the point with associative arrays and that their in-memory location is somewhat random, maybe for a reason.
 the Phobos sort function of std.algorithm
I still hope I'll survive 'till I get there ;-) thanks a lot
Oct 20 2013