digitalmars.D - Associative array dup property?
- Adrian Matoga (11/11) Jun 16 2010 I needed a duplicate of associative array so I wrote myDict.dup, which
- bearophile (11/13) Jun 16 2010 This is a possible version (untested):
- Adrian Matoga (2/2) Jun 16 2010 I also solved it with foreach but the way you wrapped it into a handy
- dsimcha (14/27) Jun 16 2010 other people have asked for it years before. I think it will be added, b...
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
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
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
== Quote from bearophile (bearophileHUGS lycos.com)'s articleAdrian Matoga:other people have asked for it years before. I think it will be added, but I presume nobody has implemented it yet.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 probablyOf 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; }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