www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Associative array dup property?

reply Adrian Matoga <epi atari8.info> writes:
I needed a duplicate of associative array so I wrote myDict.dup, which 
failed to compile (I use DMD 2.046). So I looked into the official 
language spec, which doesn't mention "dup" property for associative arrays.
The only trace I found on the Internet is in the preview of 4th chapter 
of TDPL (I'm still waiting for my copy from amazon.co.uk, which I hope 
will be dispatched before August), which, at the top of page 124, 
claims: "To create a duplicate of an associative array, use .dup, which 
works the same as for 10 arrays."
So... is it a bug or is this feature missing intentionally?
What would you recommend for concise, fast and safe surrogate?

AM
Jun 16 2010
parent reply bearophile <bearophileHUGS lycos.com> writes:
Adrian Matoga:
 So... is it a bug or is this feature missing intentionally?

I have asked for a .dup for AAs something like three years ago, and probably other people have asked for it years before. I think it will be added, but I presume nobody has implemented it yet.
 What would you recommend for concise, fast and safe surrogate?

This is a possible version (untested): TV[TK] dup(TK, TV)(TV[TK] aa) { TV[TK] result; foreach (k, v; aa) result[k] = v; return result; } Bye, bearophile
Jun 16 2010
next sibling parent Adrian Matoga <epi atari8.info> writes:
I also solved it with foreach but the way you wrapped it into a handy 
template makes it worth keeping for the future use. Thanks, bearophile!
Jun 16 2010
prev sibling parent dsimcha <dsimcha yahoo.com> writes:
== Quote from bearophile (bearophileHUGS lycos.com)'s article
 Adrian Matoga:
 So... is it a bug or is this feature missing intentionally?


presume nobody has implemented it yet.
 What would you recommend for concise, fast and safe surrogate?

TV[TK] dup(TK, TV)(TV[TK] aa) { TV[TK] result; foreach (k, v; aa) result[k] = v; return result; } Bye, bearophile

Of course that works, but you can probably do it more efficiently if you work at a lower level, inside aaA.d. For example, in terms of unnecessary memory allocations your function is roughly equivalent to using the following for duplicating a regular array: T[] dup(T)(T[] arr) { T[] ret; foreach(elem; arr) { ret ~= elem; } return ret; }
Jun 16 2010