On Tuesday, 7 January 2014 at 20:52:40 UTC, H. S. Teoh wrote:
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
Yes, I would imagine if this was not a 'one off' operation, you
would likely want to create a function. That one looks nice.
I posted my question mainly because D advertises itself as a
'multi-paradigm' language. It seems that a number of the more
experienced posters on here seem to like functional approaches
using the algorithms in std.algorithm.
However, it seems to me sometimes the obvious/simple solution
that avoids using std.algorithm results in more readable code. So
I was curious to know if using std.algorithm functions are
generally considered preferable for simple cases like this, or if
it is simply a matter of taste.
As an aside, the trade-off is even more blatant in C++ where a
simple hand-rolled solution often comes out looking so much nicer
than the STL <algorithm> alternative.