Empty non-null Associative Arrays should be trivial or even the default.
Steven Schveighoffer
schveiguy at gmail.com
Tue Aug 3 16:47:23 UTC 2021
On 8/3/21 12:28 PM, Rekel wrote:
> Feel free to disregard my previous post seems valid, as I seem to have
> misunderstood the meaning of AA's being null. (Wish I'd triple checked,
> it was an incorrect use of ) Sorry for wasting anyone's time...
>
> How can all properties still be callable with a null-AA? This surprises me.
An AA is really a struct with a pointer to an implementation struct.
Therefore, a null AA is still valid, it just has a null implementation
(which is treated as an empty one).
For example, AA length property looks like:
```d
size_t aaLength(AA *impl) {
if(impl is null) return 0;
return impl.length;
}
```
or something along those lines.
>
> Also a small sidequestion; how come remove is part of AA's definition
> while the removal of items from dynamic lists is part of the library
> instead?
A remove of an AA is an amortized O(1) operation, which makes it fast
enough to be a builtin property.
Removal from a dynamic array involves shifting elements around, and is
O(n), so it's left up to a library to do if it wishes.
>
> ---
> https://tenor.com/view/justin-timberlake-jt-bad-teacher-stupid-ifeel-stupid-gif-3547095
>
>
> For those interested, my range error was caused by the following mistake;
> ```d
> int[][int] aa;
>
> void addElement(int element) {
> aa[0] ~= element;
> }
>
> void main(string[] args) { // Works
> addElement(0);
> aa[0].writeln();
> }
>
> void main(string[] args) { // Does not work
> aa[0].writeln();
> }
> ```
AA's have a special behavior depending on whether your indexed value is
used as an rvalue or lvalue.
So for instance `writeln(aa[0])` is using `aa[0]` as an rvalue, so no
dummy element is inserted. However, `aa[0] ~= element` requires an
lvalue, so one is added if it doesn't exist.
-Steve
More information about the Digitalmars-d
mailing list