Comparison of programming languages (associative array): Difference between revisions

Content deleted Content added
+link
m fmt using AWB
Line 194:
=== D ===
[[D programming language|D]] offers direct support for associative arrays
in the core language - they are implemented as a chaining hash table with binary trees.<ref>{{Cite web|url=http://digitalmars.com/d/2.0/hash-map.html |title=Associative Arrays |accessdate=2011-02-01 |work= |date= }}</ref>. The equivalent example would be:
 
<source lang="d">
Line 299:
<pre>
mapping = NEWOBJECT("Collection")
mapping.Add("Daffodils", "flower2") && Add(object, key) - key must be character
index = mapping.GetKey("flower2") && returns the index value 1
object = mapping("flower2") && returns "Daffodils" (retrieve by key)
Line 545:
["Sally Smart"] = "555-9999",
["John Doe"] = "555-1212",
["J. Random Hacker"] = "553-1337", -- Trailing comma is OK
}
 
aTable = {
-- Table as value
subTable = { 5, 7.5, k = true }, -- key is "subTable"
-- Function as value
['John Doe'] = function (age) if age < 18 then return "Young" else return "Old!" end end,
Line 716:
</source>
 
Accessing a hash element uses the syntax <code>$hash_name{$key}</code> the key is surrounded by ''curly braces'' and the hash name is prefixed by a <code>$</code>, indicating that the hash element itself is a ''scalar'' value, even though it is part of a hash. The value of <code>$phone_book{'John Doe'}</code> is <code>'555-1212'</code>. The <code>%</code> sigil is only used when referring to the hash as a whole, such as when asking for <code>keys %phone_book</code>.
 
The list of keys and values can be extracted using the built-in functions <code>keys</code> and <code>values</code>, respectively. So, for example, to print all the keys of a hash: