Static associative array expressions

Stefan Koch uplink.coder at googlemail.com
Mon Sep 20 08:42:45 UTC 2021


On Monday, 20 September 2021 at 06:11:20 UTC, Kagamin wrote:
> On Sunday, 19 September 2021 at 11:55:04 UTC, Steven 
> Schveighoffer wrote:
>> On 9/19/21 1:43 AM, Stefan Koch wrote:
>>
>>> What do you guys think?
>>
>> I think an easier fix is just to change the call that does the 
>> AA literals to something that can be CTFEd. Right now it's an 
>> extern(C) hook that is opaque and takes void[] and TypeInfos.
>>
>> Something like:
>>
>> ```d
>> V[K] __aALiteral(V, K)(K[] keys, V[] values);
>> ```
>>
>> Then just lower the call to that, and if that is CTFEable, it 
>> works.
>>
>> -Steve
>
> Isn't that already kinda possible?
> A quick example:
> ```d
> struct StaticHashTable(TKey,TValue)
> {
> 	struct Pair { TKey key, TValue value }
> 	Pair[] items;
> 	inout(TValue) opIndex(in TKey key) pure inout
> 	{
> 		foreach(i;items)if(i.key==key)return i.value;
> 		assert(false);
> 	}
> }
>
> StaticHashTable!(TKey,TValue) make(TKey,TValue)(in TValue[TKey] 
> aa) pure
> {
> 	StaticHashTable!(TKey,TValue) s;
> 	s.items.length=8;
> 	s.items[0].key="a";
> 	s.items[0].value=aa["a"];
> 	return s;
> }
>
> immutable s=make(["a":"b","c":"d"]);
> static assert(s["a"]=="b");
> ```
> That is, you can serialize a hashtable into anything with a 
> relatively easy syntax.

Yes of course you can write a library feature that mimics what we 
already have in as a builtin.
And to make searching that efficient you can add
```d
     Value* opIndex (Key key)
     {
        size_t search_item_idx = hash(key) % n_items;
        Value* result = null;
        for(int search_gap = 1;; search_gap++)
        {
          if (items[search_item_idx].key == key)
          {
            result = &items[search_item_idx].value;
            break;
          }
          else if (items[search_item_idx].key   == Key.init
                && items[search_item_idx].value == value.init)
          {
              break;
          }
          search_item_idx = (search_item_idx + search_gap) % 
n_items;
       }
       return result;
     }
```

.... that code is lifted straight from d-runtime.
But why should the user have to have another copy of that code in 
their program?



More information about the Digitalmars-d mailing list