Content deleted Content added
Tag: Reverted |
m →F#: {{code}} |
||
(7 intermediate revisions by 6 users not shown) | |||
Line 2:
{{TOC limit|3}}
This '''
==Language support==
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 177:
Initializing an empty dictionary and adding items in [[Cobra (programming language)|Cobra]]:
{{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/>
}}
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 590:
====Map and WeakMap====
Modern JavaScript handles associative arrays, using the <code>Map</code> and <code>WeakMap</code> classes. A map does not contain any keys by default; it only contains what is explicitly put into it. The keys and values can be any type (including functions, objects, or any primitive).
=====Creation=====
A map can be initialized with all items during construction:
<syntaxhighlight lang="javascript">
const phoneBook = new Map([
["Sally Smart", "555-9999"],
["John Doe", "555-1212"],
["J. Random Hacker", "553-1337"],
]);
</syntaxhighlight>
Alternatively, you can initialize an empty map and then add items:
<syntaxhighlight lang="javascript">
const phoneBook = new Map();
phoneBook.set("Sally Smart", "555-9999");
phoneBook.set("John Doe", "555-1212");
phoneBook.set("J. Random Hacker", "553-1337");
</syntaxhighlight>
=====Access by key=====
Line 616 ⟶ 636:
</syntaxhighlight>
====Object====
An object is similar to a map—both let you set keys to values, retrieve those values, delete keys, and detect whether a value is stored at a key. For this reason (and because there were no built-in alternatives), objects historically have been used as maps.
However, there are important differences that make a map preferable in certain cases. In JavaScript an object is a mapping from property names to values—that is, an associative array with one caveat: the keys of an object must be either a string or a symbol (native objects and primitives implicitly converted to a string keys are allowed). Objects also include one feature unrelated to associative arrays: an object has a prototype, so it contains default keys that could conflict with user-defined keys. So, doing a lookup for a property will point the lookup to the prototype's definition if the object does not define the property.
An object literal is written as <code>{ property1: value1, property2: value2, ... }</code>. For example:
<syntaxhighlight lang="javascript">
const myObject = {
"Sally Smart": "555-9999",
"John Doe": "555-1212",
"J. Random Hacker": "553-1337",
};
</syntaxhighlight>
To prevent the lookup from using the prototype's properties, you can use the <code>Object.setPrototypeOf</code> function:
<syntaxhighlight lang=JavaScript>
Object.setPrototypeOf(myObject, null);
</syntaxhighlight>
As of ECMAScript 5 (ES5), the prototype can also be bypassed by using <code>Object.create(null)</code>:
<syntaxhighlight lang=JavaScript>
const myObject = Object.create(null);
Object.assign(myObject, {
"Sally Smart": "555-9999",
"John Doe": "555-1212",
"J. Random Hacker": "553-1337",
});
</syntaxhighlight>
If the property name is a valid identifier, the quotes can be omitted, e.g.:
<syntaxhighlight lang=JavaScript>
const myOtherObject = { foo: 42, bar: false };
</syntaxhighlight>
Lookup is written using property-access notation, either square brackets, which always work, or dot notation, which only works for identifier keys:
<syntaxhighlight lang=JavaScript>
myObject["John Doe"]
myOtherObject.foo
</syntaxhighlight>
You can also loop through all enumerable properties and associated values as follows (a for-in loop):
<syntaxhighlight lang=JavaScript>
for (const property in myObject) {
const value = myObject[property];
console.log(`myObject[${property}] = ${value}`);
}
</syntaxhighlight>
Or (a for-of loop):
<syntaxhighlight lang=JavaScript>
for (const [property, value] of Object.entries(myObject)) {
console.log(`${property} = ${value}`);
}
</syntaxhighlight>
A property can be removed as follows:
<syntaxhighlight lang=JavaScript>
delete myObject["Sally Smart"];
</syntaxhighlight>
As mentioned before, properties are strings and symbols. Since every native object and primitive can be implicitly converted to a string, you can do:
<syntaxhighlight lang=JavaScript>
myObject[1] // key is "1"; note that myObject[1] == myObject["1"]
myObject[["a", "b"]] // key is "a,b"
myObject[{ toString() { return "hello world"; } }] // key is "hello world"
</syntaxhighlight>
In modern JavaScript it's considered bad form to use the Array type as an associative array. Consensus is that the Object type and <code>Map</code>/<code>WeakMap</code> classes are best for this purpose. The reasoning behind this is that if Array is extended via prototype and Object is kept pristine, for and for-in loops will work as expected on associative 'arrays'. This issue has been brought to the fore by the popularity of JavaScript frameworks that make heavy and sometimes indiscriminate use of prototypes to extend JavaScript's inbuilt types.
See [http://blog.metawrap.com/2006/05/30/june-6th-is-javascript-array-and-object-prototype-awareness-day/ JavaScript Array And Object Prototype Awareness Day] for more information on the issue.
===Julia===
Line 624 ⟶ 723:
Declare dictionary:
<syntaxhighlight lang="julia">
</syntaxhighlight>
Access element:
<syntaxhighlight lang="julia">
phonebook["Sally Smart"]
</syntaxhighlight>
Add element:
<syntaxhighlight lang="julia">
</syntaxhighlight>
Delete element:
<syntaxhighlight lang="julia">
</syntaxhighlight>
Get keys and values as [[Iterator#Implicit iterators|iterables]]:
<syntaxhighlight lang="julia">
</syntaxhighlight>
===KornShell 93, and compliant shells===
Line 650 ⟶ 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 699 ⟶ 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 971 ⟶ 1,074:
<syntaxhighlight lang="mathematica">
</syntaxhighlight>
Line 979 ⟶ 1,082:
<syntaxhighlight lang="mathematica">
</syntaxhighlight>
Line 985 ⟶ 1,088:
<syntaxhighlight lang="mathematica">
</syntaxhighlight>
Line 1,122 ⟶ 1,225:
<syntaxhighlight lang=Java>
String[String] phoneBook = {
"Sally Smart" -> "555-9999",
"John Doe" -> "555-1212",
"J. Random Hacker" -> "553-1337"
};
Line 1,131 ⟶ 1,234:
// iterate over the values
for (String number : phoneBook) {
System.out.println(number);
}
Line 1,138 ⟶ 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,149 ⟶ 1,252:
<syntaxhighlight lang=Java>
</syntaxhighlight>
Line 1,984 ⟶ 2,087:
"J. Random Hacker": "555-1337"
}
</syntaxhighlight>
=== TOML ===
[[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>
|