Content deleted Content added
→Visual Basic: fix syntaxhighlight error |
m →F#: {{code}} |
||
(20 intermediate revisions by 13 users not shown) | |||
Line 2:
{{TOC limit|3}}
This '''
==Language support==
Line 8:
The following is a comparison of [[associative array]]s (also "mapping", "hash", and "dictionary") in various programming languages.
===
[[
For example:
Line 29:
The user can search for elements in an associative array, and delete elements from the array.
The following shows how multi-dimensional associative arrays can be simulated in standard
<syntaxhighlight lang=awk>
Line 47:
There is no standard implementation of associative arrays in [[C (programming language)|C]], but a 3rd-party library, C Hash Table, with BSD license, is available.<ref>[https://web.archive.org/web/20071015024120/http://www.cl.cam.ac.uk/~cwc22/hashtable/ here], archived [https://web.archive.org/web/20040902160534/http://www.cl.cam.ac.uk/~cwc22/hashtable/ here], with the source code available [https://github.com/davidar/c-hashtable/ here]. [[POSIX]] 1003.1-2001 describes the functions <code>hcreate()</code>, <code>hdestroy()</code> and <code>hsearch()</code></ref>
Another 3rd-party library, uthash, also creates associative arrays from C structures. A structure represents a value, and one of the structure fields serves as the key.<ref>{{cite web |title=uthash: a hash table for C structures |url=
Finally, the [[GLib]] library also supports associative arrays, along with many other advanced data types and is the recommended implementation of the GNU Project.<ref>{{cite web |title=Hash Tables |url=https://developer.gnome.org/glib/stable/glib-Hash-Tables.html |website=Gnome Developer |access-date=3 August 2020}}</ref>
Line 174:
In C++, the <code>std::map</code> class is [[Generic programming#Templates in C.2B.2B|templated]] which allows the [[data type]]s of keys and values to be different for different <code>map</code> instances. For a given instance of the <code>map</code> class the keys must be of the same base type. The same must be true for all of the values. Although <code>std::map</code> is typically implemented using a [[self-balancing binary search tree]], C++11 defines a second map called <code>[[std::unordered_map]]</code>, which has the algorithmic characteristics of a hash table. This is a common vendor extension to the [[Standard Template Library]] (STL) as well, usually called <code>hash_map</code>, available from such implementations as SGI and STLPort.
===
Initializing an empty dictionary and adding items in [[Cobra (programming language)|Cobra]]:▼
A structure in [[CFML]] is equivalent to an associative array:▼
{{sxhl|2=python|1=<nowiki/>▼
}}▼
Alternatively, a dictionary can be initialized with all items during construction:▼
{{sxhl|2=python|1=<nowiki/>▼
}}▼
The dictionary can be enumerated by a for-loop, but there is no guaranteed order:▼
{{sxhl|2=python|1=<nowiki/>▼
}}▼
===ColdFusion Markup Language===
<syntaxhighlight lang=CFS>
Line 188 ⟶ 212:
writeDump(phoneBook); // entire struct
</syntaxhighlight>
===Cobra===▼
▲Initializing an empty dictionary and adding items in [[Cobra (programming language)|Cobra]]:
▲{{sxhl|2=python|1=<nowiki/>
▲ dic as Dictionary<of String, String> = Dictionary<of String, String>()
▲ dic.add('Sally Smart', '555-9999')
▲ dic.add('John Doe', '555-1212')
▲ dic.add('J. Random Hacker', '553-1337')
▲ assert dic['Sally Smart'] == '555-9999'
▲}}
▲Alternatively, a dictionary can be initialized with all items during construction:
▲{{sxhl|2=python|1=<nowiki/>
▲ dic = {
▲ 'Sally Smart':'555-9999',
▲ 'John Doe':'555-1212',
▲ 'J. Random Hacker':'553-1337'
▲ }
▲}}
▲The dictionary can be enumerated by a for-loop, but there is no guaranteed order:
▲{{sxhl|2=python|1=<nowiki/>
▲ for key, val in dic
▲ print "[key]'s phone number is [val]"
▲}}
===D===
Line 243:
===Delphi===
[[Delphi (
<syntaxhighlight lang="delphi">
Line 265:
</syntaxhighlight>
<syntaxhighlight lang="delphi">
Line 375:
===F#===
===={{code|Map<'Key,'Value>}}====
At runtime, [[F Sharp (programming language)|F#]] provides the <code>Collections.Map<'Key,'Value></code> type, which is an immutable [[AVL tree]].
Line 391:
=====Access by key=====
Values can be looked up via one of the <code>Map</code> members, such as its indexer or <code>Item</code> property (which throw an [[Exception handling|exception]] if the key does not exist) or the <code>TryFind</code> function, which returns an [[option type]] with a value of
<syntaxhighlight lang="fsharp">
Line 407:
In both examples above, the <code>sallyNumber</code> value would contain the string <code>"555-9999"</code>.
===={{code|Dictionary<'TKey,'TValue>}}====
Because F# is a .NET language, it also has access to features of the [[.NET Framework]], including the {{code|System.Collections.Generic.Dictionary<'TKey,'TValue>|f#}} type (which is implemented as a [[hash table]]), which is the primary associative array type used in C# and Visual Basic. This type may be preferred when writing code that is intended to operate with other languages on the .NET Framework, or when the performance characteristics of a hash table are preferred over those of an AVL tree.
=====Creation=====
The <code>dict</code> function provides a means of conveniently creating a .NET dictionary that is not intended to be mutated; it accepts a sequence of tuples and returns an immutable object that implements
<syntaxhighlight lang="fsharp">
Line 508:
===Haskell===
The [[
<syntaxhighlight lang="haskell">
Line 520:
Note that the lookup function returns a "Maybe" value, which is "Nothing" if not found, or "Just 'result{{' "}} when found.
The [[Glasgow Haskell Compiler
One is polymorphic functional maps (represented as immutable balanced binary trees):
Line 553:
Just "555-1212"
Lists of pairs and functional maps both provide a purely functional interface, which is more idiomatic in Haskell. In contrast, hash tables provide an imperative interface in the [[
===Java===
Line 567:
The {{Javadoc:SE|java/util|Map|get(java.lang.Object)|name=get}} method is used to access a key; for example, the value of the expression <code>phoneBook.get("Sally Smart")</code> is <code>"555-9999"</code>. This code uses a hash map to store the associative array, by calling the constructor of the {{Javadoc:SE|java/util|HashMap}} class. However, since the code only uses methods common to the interface {{Javadoc:SE|java/util|Map}}, a self-balancing binary tree could be used by calling the constructor of the {{Javadoc:SE|java/util|TreeMap}} class (which implements the subinterface {{Javadoc:SE|java/util|SortedMap}}), without changing the definition of the <code>phoneBook</code> variable, or the rest of the code, or using other underlying data structures that implement the <code>Map</code> interface.
The hash function in Java, used by HashMap and HashSet, is provided by the {{Javadoc:SE|java/lang|Object|hashCode()}} method. Since every class in Java [[Inheritance (
The <code>Object</code> class also contains the {{Javadoc:SE|name=equals(Object)|java/lang|Object|equals(java.lang.Object)}} method, which tests an object for equality with another object. Hashed data structures in Java rely on objects maintaining the following contract between their <code>hashCode()</code> and <code>equals()</code> methods:
Line 723:
Declare dictionary:
<syntaxhighlight lang="julia">
</syntaxhighlight>
Access element:
<syntaxhighlight lang="julia">
</syntaxhighlight>
Add element:
<syntaxhighlight lang="julia">
</syntaxhighlight>
Delete element:
<syntaxhighlight lang="julia">
</syntaxhighlight>
▲ delete!(phonebook, "Sally Smart")
<syntaxhighlight lang="julia">
▲Get keys and values as [[Iterator#Implicit_iterators|iterables]]:
</syntaxhighlight>
▲ keys(phonebook)
▲ values(phonebook)
===KornShell 93, and compliant shells===
Line 749 ⟶ 754:
Definition:
<syntaxhighlight lang="ksh">
▲ phonebook=(["Sally Smart"]="555-9999" ["John Doe"]="555-1212" ["[[J. Random Hacker]]"]="555-1337");
</syntaxhighlight>
Dereference:
<syntaxhighlight lang="ksh">
</syntaxhighlight>
Line 798 ⟶ 802:
</syntaxhighlight>
Searching for an entry by its key is performed via <code>assoc</code>, which might be configured for the test predicate and direction, especially searching the association list from its end to its front. The result, if positive, returns the entire entry cons, not only its value. Failure to obtain a matching key
<syntaxhighlight lang=Lisp>
Line 1,070 ⟶ 1,074:
<syntaxhighlight lang="mathematica">
</syntaxhighlight>
Line 1,078 ⟶ 1,082:
<syntaxhighlight lang="mathematica">
</syntaxhighlight>
Line 1,084 ⟶ 1,088:
<syntaxhighlight lang="mathematica">
</syntaxhighlight>
Line 1,137 ⟶ 1,141:
</syntaxhighlight>
In Mac OS X 10.5+ and iPhone OS, dictionary keys can be enumerated more concisely using the <code>NSFastEnumeration</code> construct:<ref>{{cite web |title=NSFastEnumeration Protocol Reference |url=https://developer.apple.com/documentation/Cocoa/Reference/NSFastEnumeration_protocol/ |date=2011 |archive-url=https://web.archive.org/web/20160313082808/https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSFastEnumeration_protocol/ |archive-date=13 March 2016 |website=Mac Developer Library |access-date=3 August 2020}}</ref>
<syntaxhighlight lang=ObjC>
Line 1,221 ⟶ 1,225:
<syntaxhighlight lang=Java>
String[String] phoneBook = {
"Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
"J. Random Hacker" -> "553-1337"
};
Line 1,230 ⟶ 1,234:
// iterate over the values
for (String number : phoneBook) {
System.out.println(number);
}
Line 1,237 ⟶ 1,241:
// iterate over the keys
for (String name : phoneBook.keys) {
System.out.println(name + " -> " + phoneBook[name]);
}
// phoneBook[name] access a value by a key (it looks like java array access)
Line 1,248 ⟶ 1,252:
<syntaxhighlight lang=Java>
</syntaxhighlight>
Line 1,265 ⟶ 1,269:
</syntaxhighlight>
Accessing a hash element uses the syntax <code>$hash_name{$key}</code> – the key is surrounded by [[Bracket#
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:
Line 1,371 ⟶ 1,375:
===PHP===
[[PHP]]'s built-in array type is, in reality, an associative array. Even when using numerical indexes, PHP internally stores arrays as associative arrays.<ref>About the implementation of [http://se.php.net/manual/en/language.types.array.php Arrays] in PHP</ref> So, PHP can have non-consecutively numerically
An associative array can be declared using the following syntax:
Line 1,577 ⟶ 1,581:
</syntaxhighlight>
Python 2.7 and 3.x also support
<syntaxhighlight lang="python">
Line 1,733 ⟶ 1,737:
===S-Lang===
[[
<syntaxhighlight lang="text">
Line 2,083 ⟶ 2,087:
"J. Random Hacker": "555-1337"
}
</syntaxhighlight>
[[TOML]] is designed to map directly to a hash map. TOML refers to associative arrays as tables. Tables within TOML can be expressed in either an "unfolded" or an inline approach. Keys can only be strings.<syntaxhighlight lang="toml">[phonebook]
"Sally Smart" = "555-9999"
"John Doe" = "555-1212"
"J. Random Hacker" = "555-1337"</syntaxhighlight><syntaxhighlight lang="toml">
phonebook = { "Sally Smart" = "555-9999", "John Doe" = "555-1212", "J. Random Hacker" = "555-1337" }
</syntaxhighlight>
|