February 09, 2023
On Thursday, 9 February 2023 at 07:19:08 UTC, Alexander Zhirov wrote:
>> foo.byPair
>>  .array
>>  .sort!((a, b) => a.key < b.key)
>>  .map!(a => a.value);
>
> Is it possible to specify in `map` to return the result `[a.key] = a.value`? To make the result look like `[key:[val], key:[val]]`

Wow. This is an old thread....

.. anyway... how about making custom strings out of the KV pairs:

void main()
{
    import std.conv : to;
    import std.algorithm : sort;
    import std.stdio : writeln;

    auto foo = ["VXE":8, "BZP":5, "JLC":2];

    string[] orderedKeyPairSet;

    foreach (ref kv; foo.byKeyValue)
    {
        orderedKeyPairSet ~= kv.key.to!string ~ ":" ~ kv.value.to!string;

    }

    orderedKeyPairSet.sort;

    foreach(ref str; orderedKeyPairSet)
        writeln(str);

}

/*
output:

BZP:5
JLC:2
VXE:8

*/

February 09, 2023
On 2/8/23 23:19, Alexander Zhirov wrote:
>> foo.byPair
>>  .array
>>  .sort!((a, b) => a.key < b.key)
>>  .map!(a => a.value);
>
> Is it possible to specify in `map` to return the result `[a.key] =
> a.value`? To make the result look like `[key:[val], key:[val]]`

map can return a tuple and std.array.assocArray can make an associative array from those tuples:

import std;

void main() {
    auto aa = iota(10)
              .map!(n => tuple(n, n * n))
              .assocArray;
    writeln("Necessarily unsorted:\n", aa);
}

However, as the original question started with an associative array anyway, I don't think I understand your question correctly. :)

If you are asking whether an associative array can store in sorted key order, then no, it's impossible because associative arrays are hash tables, which can't provide that.

But we can visit the elements in sorted order if we sort those keys ourselves:

    auto keys = aa
                .keys  // <- Makes an array by copying the keys
                .sort;

    writeln("In order:");
    foreach (k; keys) {
        writeln(k, ": ", aa[k]);
    }

Ali

1 2
Next ›   Last »