Simplest way to create an array from an associative array which its contains keys and values?

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jan 7 12:51:11 PST 2014


On Tue, Jan 07, 2014 at 08:38:10PM +0000, Craig Dillabaugh wrote:
[...]
> As someone with little experience with functional programming, I am
> just curious - having browsed through the thread - if the various
> solutions proposed here would really be considered more 'idiomatic'
> D. Or if they were posted because the OP asked about avoiding the
> foreach() loop.
> 
> In other words while:
> 
>     auto range = aa.byKey.map!(a => chain(a.only, aa[a].only));
>     string[] array = range.join;
> 
> Saves a few lines of code, and looks cooler, it seems that the
> trivial foreach loop version is very easy:
> 
> string[] array;
> 
> foreach (key, value; aa) {
> 	array ~= key;
> 	array ~= value;
> }
[...]

Even better, encapsulate this in a function:

	CommonType!(K,V)[] aaToArray(K,V)(V[K] aa)
		if (is(CommonType!(V, K)))
	{
		typeof(return) result;
		foreach (key, value; aa) {
			result ~= key;
			result ~= value;
		}
		return result;
	}

Then you can use it in a single line next time:

	string[] arr = aaToArray(["a": "aa", "b" : "bb"]);
	int[] arr = aaToArray([1: 2, 3: 4]);
	... // etc.


T

-- 
Real men don't take backups. They put their source on a public
FTP-server and let the world mirror it. -- Linus Torvalds


More information about the Digitalmars-d-learn mailing list