Associative array mutation of a value

Idan Arye GenericNPC at gmail.com
Fri Feb 7 12:22:53 PST 2014


On Thursday, 6 February 2014 at 14:15:47 UTC, bearophile wrote:
> Recently Erlang language has added several things:
> http://joearms.github.io/2014/02/01/big-changes-to-erlang.html
>
> One interesting change is the syntax to handle associative 
> arrays (that are meant to be used a little like records):
>
>> Updating a map is done as follows:
>> 
>> NewX = X#{ key1 => Val1, ... KeyN := ValN, ...}
>
> X is the old associative array. "=>" adds a mew key, while ":=" 
> updates an already existing key, and if it's not present an 
> error is generated. So a spelling mistake cannot accidentally 
> introduce a new key if you want to update some value. This 
> avoids a common mistake.
>
> I am not suggesting to add a new syntax to D, but perhaps a 
> simple "AA.update(key, val)" function in the object module can 
> be useful.
>
> Bye,
> bearophile

I'm always for little helper functions, but I don't think 
Erlang's idiom of using maps as records is good for D. That model 
works well with dynamic typing, where record types are 
meaningless and only their structure is important(JavaScript is 
fine example). With static typing it's better to declare a type 
for the record, so whether the field you are trying to set exists 
or not can be checked at compile-time.

Besides, the usefulness of maps-as-records will be quite limited 
in D, since associative arrays has a fixed value type. To store 
different types in different fields, we'll need to stringly-type 
them(very bad!), use pointers abd casting(not that bad but still 
bad!) or use Variant - which is better than the first two 
solutions but still not as good as simply using structs or 
classes.


More information about the Digitalmars-d mailing list