Associative array/Creation: Difference between revisions
Content added Content deleted
(Added 4tH example) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 14: | Line 14: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
< |
<syntaxhighlight lang=11l>V dict = [‘key1’ = 1, ‘key2’ = 2] |
||
V value2 = dict[‘key2’]</ |
V value2 = dict[‘key2’]</syntaxhighlight> |
||
=={{header|8th}}== |
=={{header|8th}}== |
||
8th has 'maps' as built-in data types, and can use JSON to describe them: |
8th has 'maps' as built-in data types, and can use JSON to describe them: |
||
< |
<syntaxhighlight lang=Forth> |
||
{ "one" : 1, "two" : "bad" } |
{ "one" : 1, "two" : "bad" } |
||
</syntaxhighlight> |
|||
</lang> |
|||
Alternatively, they can be created in code: |
Alternatively, they can be created in code: |
||
< |
<syntaxhighlight lang=Forth> |
||
m:new "one" 1 m:! "two" "bad" m:! |
m:new "one" 1 m:! "two" "bad" m:! |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |
||
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }} |
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }} |
||
< |
<syntaxhighlight lang=AArch64 Assembly> |
||
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ |
/* ARM assembly AARCH64 Raspberry PI 3B or android 64 bits */ |
||
/* program hashmap64.s */ |
/* program hashmap64.s */ |
||
Line 425: | Line 425: | ||
.include "../includeARM64.inc" |
.include "../includeARM64.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
Because ActionScript does not have associative arrays in the normal sense, Object objects are used instead and keys are simply properties on those objects. |
Because ActionScript does not have associative arrays in the normal sense, Object objects are used instead and keys are simply properties on those objects. |
||
< |
<syntaxhighlight lang=actionscript>var map:Object = {key1: "value1", key2: "value2"}; |
||
trace(map['key1']); // outputs "value1" |
trace(map['key1']); // outputs "value1" |
||
Line 437: | Line 437: | ||
// More keys and values can then be added |
// More keys and values can then be added |
||
map['key3'] = "value3"; |
map['key3'] = "value3"; |
||
trace(map['key3']); // outputs "value3"</ |
trace(map['key3']); // outputs "value3"</syntaxhighlight> |
||
''Note: The Object only supports String keys. To use an object as a key, try the flash.utils.Dictionary class.'' |
''Note: The Object only supports String keys. To use an object as a key, try the flash.utils.Dictionary class.'' |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
{{works with|GNAT|GPL 2007}} |
{{works with|GNAT|GPL 2007}} |
||
< |
<syntaxhighlight lang=ada>with Ada.Containers.Ordered_Maps; |
||
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; |
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; |
||
with Ada.Text_IO; |
with Ada.Text_IO; |
||
Line 474: | Line 474: | ||
Value := Color_Map.Element(To_Unbounded_String("Yellow")); |
Value := Color_Map.Element(To_Unbounded_String("Yellow")); |
||
Ada.Text_IO.Put_Line("Yellow:" & Integer'Image(Value)); |
Ada.Text_IO.Put_Line("Yellow:" & Integer'Image(Value)); |
||
end Associative_Array;</ |
end Associative_Array;</syntaxhighlight> |
||
=={{header|Aikido}}== |
=={{header|Aikido}}== |
||
Aikido provides a native <em>map</em> for associative arrays. You can create them using a map literal and you can insert and remove items on the fly. |
Aikido provides a native <em>map</em> for associative arrays. You can create them using a map literal and you can insert and remove items on the fly. |
||
< |
<syntaxhighlight lang=aikido> |
||
var names = {} // empty map |
var names = {} // empty map |
||
names["foo"] = "bar" |
names["foo"] = "bar" |
||
Line 498: | Line 498: | ||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
Aime records are heterogenous associative arrays. No creation procedure is required, declaration is fine. |
Aime records are heterogenous associative arrays. No creation procedure is required, declaration is fine. |
||
<lang |
<syntaxhighlight lang=aime>record r;</syntaxhighlight> |
||
< |
<syntaxhighlight lang=aime>r_put(r, "A", 33); # an integer value |
||
r_put(r, "C", 2.5); # a real value |
r_put(r, "C", 2.5); # a real value |
||
r_put(r, "B", "associative"); # a string value</ |
r_put(r, "B", "associative"); # a string value</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Line 514: | Line 514: | ||
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}} |
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}} |
||
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}} |
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}} |
||
< |
<syntaxhighlight lang=algol68>main:( |
||
MODE COLOR = BITS; |
MODE COLOR = BITS; |
||
Line 583: | Line 583: | ||
printf(($g$,"values: ", comma sep, value OF color map items, $l$)) |
printf(($g$,"values: ", comma sep, value OF color map items, $l$)) |
||
)</ |
)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 600: | Line 600: | ||
Creating a new empty map of String to String: |
Creating a new empty map of String to String: |
||
< |
<syntaxhighlight lang=apex>// Cannot / Do not need to instantiate the algorithm implementation (e.g, HashMap). |
||
Map<String, String> strMap = new Map<String, String>(); |
Map<String, String> strMap = new Map<String, String>(); |
||
strMap.put('a', 'aval'); |
strMap.put('a', 'aval'); |
||
Line 608: | Line 608: | ||
System.assertEquals( 'bval', strMap.get('b') ); |
System.assertEquals( 'bval', strMap.get('b') ); |
||
// String keys are case-sensitive |
// String keys are case-sensitive |
||
System.assert( !strMap.containsKey('A') );</ |
System.assert( !strMap.containsKey('A') );</syntaxhighlight> |
||
Creating a new map of String to String with values initialized: |
Creating a new map of String to String with values initialized: |
||
< |
<syntaxhighlight lang=apex>Map<String, String> strMap = new Map<String, String>{ |
||
'a' => 'aval', |
'a' => 'aval', |
||
'b' => 'bval' |
'b' => 'bval' |
||
Line 617: | Line 617: | ||
System.assert( strMap.containsKey('a') ); |
System.assert( strMap.containsKey('a') ); |
||
System.assertEquals( 'bval', strMap.get('b') );</ |
System.assertEquals( 'bval', strMap.get('b') );</syntaxhighlight> |
||
=={{header|APL}}== |
=={{header|APL}}== |
||
{{works with|Dyalog APL}} |
{{works with|Dyalog APL}} |
||
< |
<syntaxhighlight lang=apl>⍝ Create a namespace ("hash") |
||
X←⎕NS ⍬ |
X←⎕NS ⍬ |
||
Line 642: | Line 642: | ||
sales.revenue |
sales.revenue |
||
4109.6 |
4109.6 |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{works with|GNU APL}} |
{{works with|GNU APL}} |
||
< |
<syntaxhighlight lang=apl> |
||
⍝ Assign some names |
⍝ Assign some names |
||
X.this←'that' |
X.this←'that' |
||
Line 672: | Line 672: | ||
sales.revenue |
sales.revenue |
||
4109.6 |
4109.6 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|App Inventor}}== |
=={{header|App Inventor}}== |
||
Line 681: | Line 681: | ||
=={{header|ARM Assembly}}== |
=={{header|ARM Assembly}}== |
||
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}} |
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}} |
||
< |
<syntaxhighlight lang=ARM Assembly> |
||
/* ARM assembly Raspberry PI or android 32 bits */ |
/* ARM assembly Raspberry PI or android 32 bits */ |
||
/* program hashmap.s */ |
/* program hashmap.s */ |
||
Line 1,054: | Line 1,054: | ||
.include "../affichage.inc" |
.include "../affichage.inc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang=rebol>; create a dictionary |
||
d: #[ |
d: #[ |
||
name: "john" |
name: "john" |
||
Line 1,064: | Line 1,064: | ||
] |
] |
||
print d</ |
print d</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,078: | Line 1,078: | ||
=== Persistent association lists === |
=== Persistent association lists === |
||
The following implementation includes set, get, and delete, and also "generators", which are like iterators except they are closures rather than regular objects. |
The following implementation includes set, get, and delete, and also "generators", which are like iterators except they are closures rather than regular objects. |
||
< |
<syntaxhighlight lang=ATS>(*------------------------------------------------------------------*) |
||
#define ATS_DYNLOADFLAG 0 |
#define ATS_DYNLOADFLAG 0 |
||
Line 1,303: | Line 1,303: | ||
end |
end |
||
(*------------------------------------------------------------------*)</ |
(*------------------------------------------------------------------*)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,324: | Line 1,324: | ||
Because the hash table is an AVL tree, performance will tend to be logarithmic. This assumes a good hash function, of course. With a bad hash function, performance may be linear. |
Because the hash table is an AVL tree, performance will tend to be logarithmic. This assumes a good hash function, of course. With a bad hash function, performance may be linear. |
||
< |
<syntaxhighlight lang=ATS>(*------------------------------------------------------------------*) |
||
#define ATS_DYNLOADFLAG 0 |
#define ATS_DYNLOADFLAG 0 |
||
Line 1,902: | Line 1,902: | ||
end |
end |
||
(*------------------------------------------------------------------*)</ |
(*------------------------------------------------------------------*)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,917: | Line 1,917: | ||
=== True arrays === |
=== True arrays === |
||
[[AutoHotkey_L]] has [http://ahkscript.org/docs/Objects.htm Objects] which function as associative arrays. |
[[AutoHotkey_L]] has [http://ahkscript.org/docs/Objects.htm Objects] which function as associative arrays. |
||
< |
<syntaxhighlight lang=AutoHotkey>associative_array := {key1: "value 1", "Key with spaces and non-alphanumeric characters !*+": 23} |
||
MsgBox % associative_array.key1 |
MsgBox % associative_array.key1 |
||
. "`n" associative_array["Key with spaces and non-alphanumeric characters !*+"]</ |
. "`n" associative_array["Key with spaces and non-alphanumeric characters !*+"]</syntaxhighlight> |
||
=== Legacy versions === |
=== Legacy versions === |
||
[[AutoHotkey_Basic]] does not have typical arrays. |
[[AutoHotkey_Basic]] does not have typical arrays. |
||
However, variable names can be concatenated, simulating associative arrays. |
However, variable names can be concatenated, simulating associative arrays. |
||
< |
<syntaxhighlight lang=AutoHotkey>arrayX1 = first |
||
arrayX2 = second |
arrayX2 = second |
||
arrayX3 = foo |
arrayX3 = foo |
||
arrayX4 = bar |
arrayX4 = bar |
||
Loop, 4 |
Loop, 4 |
||
Msgbox % arrayX%A_Index%</ |
Msgbox % arrayX%A_Index%</syntaxhighlight> |
||
=={{header|AutoIt}}== |
=={{header|AutoIt}}== |
||
See '''[https://msdn.microsoft.com/en-us/library/x4k5wbx4.aspx here]''' in the MSDN the reference for the Dictionary object that can be used in VBA. The following example shows how to create a dictionary, add/remove keys, change a key or a value, and check the existence of a key. |
See '''[https://msdn.microsoft.com/en-us/library/x4k5wbx4.aspx here]''' in the MSDN the reference for the Dictionary object that can be used in VBA. The following example shows how to create a dictionary, add/remove keys, change a key or a value, and check the existence of a key. |
||
< |
<syntaxhighlight lang=AutoIt>; Associative arrays in AutoIt. |
||
; All the required functions are below the examples. |
; All the required functions are below the examples. |
||
Line 2,059: | Line 2,059: | ||
;; End AA Functions. |
;; End AA Functions. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Arrays in AWK are indeed associative arrays. |
Arrays in AWK are indeed associative arrays. |
||
< |
<syntaxhighlight lang=awk>BEGIN { |
||
a["red"] = 0xff0000 |
a["red"] = 0xff0000 |
||
a["green"] = 0x00ff00 |
a["green"] = 0x00ff00 |
||
Line 2,078: | Line 2,078: | ||
print ( "red" in a ) # print 0 |
print ( "red" in a ) # print 0 |
||
print ( "blue" in a ) # print 1 |
print ( "blue" in a ) # print 1 |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Babel}}== |
=={{header|Babel}}== |
||
< |
<syntaxhighlight lang=babel> |
||
(("foo" 13) |
(("foo" 13) |
||
("bar" 42) |
("bar" 42) |
||
("baz" 77)) ls2map !</ |
("baz" 77)) ls2map !</syntaxhighlight> |
||
=={{header|BaCon}}== |
=={{header|BaCon}}== |
||
< |
<syntaxhighlight lang=qbasic>DECLARE associative ASSOC STRING |
||
associative("abc") = "first three" |
associative("abc") = "first three" |
||
associative("xyz") = "last three" |
associative("xyz") = "last three" |
||
PRINT associative("xyz")</ |
PRINT associative("xyz")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,103: | Line 2,103: | ||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
< |
<syntaxhighlight lang=BASIC256>global values$, keys$ |
||
dim values$[1] |
dim values$[1] |
||
dim keys$[1] |
dim keys$[1] |
||
Line 2,208: | Line 2,208: | ||
next n |
next n |
||
return "" |
return "" |
||
end function</ |
end function</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>a apple |
<pre>a apple |
||
Line 2,222: | Line 2,222: | ||
This is cheating, I'm sure of it. |
This is cheating, I'm sure of it. |
||
< |
<syntaxhighlight lang=dos>::assocarrays.cmd |
||
@echo off |
@echo off |
||
setlocal ENABLEDELAYEDEXPANSION |
setlocal ENABLEDELAYEDEXPANSION |
||
Line 2,246: | Line 2,246: | ||
echo %1 = %2 |
echo %1 = %2 |
||
goto :eof |
goto :eof |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 2,259: | Line 2,259: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang=bbcbasic> REM Store some values with their keys: |
||
PROCputdict(mydict$, "FF0000", "red") |
PROCputdict(mydict$, "FF0000", "red") |
||
PROCputdict(mydict$, "00FF00", "green") |
PROCputdict(mydict$, "00FF00", "green") |
||
Line 2,279: | Line 2,279: | ||
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2 |
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2 |
||
J% = INSTR(dict$, CHR$(0), I%) |
J% = INSTR(dict$, CHR$(0), I%) |
||
= MID$(dict$, I%, J% - I%)</ |
= MID$(dict$, I%, J% - I%)</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
The hash is the only built-in Bracmat class. It is best used for e.g. a large dictionary, when manipulation of a very long list of key/value pairs with pattern matching would become too CPU-intensive. The same key can be stored with different values, as the example shows. If that is not desirable, the key (and its value) should be removed first. |
The hash is the only built-in Bracmat class. It is best used for e.g. a large dictionary, when manipulation of a very long list of key/value pairs with pattern matching would become too CPU-intensive. The same key can be stored with different values, as the example shows. If that is not desirable, the key (and its value) should be removed first. |
||
< |
<syntaxhighlight lang=bracmat> new$hash:?myhash |
||
& (myhash..insert)$(title."Some title") |
& (myhash..insert)$(title."Some title") |
||
& (myhash..insert)$(formula.a+b+x^7) |
& (myhash..insert)$(formula.a+b+x^7) |
||
Line 2,292: | Line 2,292: | ||
& (myhash..remove)$formula |
& (myhash..remove)$formula |
||
& (myhash..insert)$(formula.x^2+y^2) |
& (myhash..insert)$(formula.x^2+y^2) |
||
& out$(myhash..find)$formula;</ |
& out$(myhash..find)$formula;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>(fruit.melons bananas) (fruit.apples oranges kiwis) |
<pre>(fruit.melons bananas) (fruit.apples oranges kiwis) |
||
Line 2,298: | Line 2,298: | ||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang=brat>h = [:] #Empty hash |
||
h[:a] = 1 #Assign value |
h[:a] = 1 #Assign value |
||
Line 2,305: | Line 2,305: | ||
h2 = [a: 1, b: [1 2 3], 10 : "ten"] #Initialized hash |
h2 = [a: 1, b: [1 2 3], 10 : "ten"] #Initialized hash |
||
h2[:b][2] #Returns 3</ |
h2[:b][2] #Returns 3</syntaxhighlight> |
||
=={{header|C}}== |
=={{header|C}}== |
||
Line 2,312: | Line 2,312: | ||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
'''Platform:''' [[.NET]] 1.x |
'''Platform:''' [[.NET]] 1.x |
||
< |
<syntaxhighlight lang=csharp>System.Collections.HashTable map = new System.Collections.HashTable(); |
||
map["key1"] = "foo";</ |
map["key1"] = "foo";</syntaxhighlight> |
||
'''Platform:''' [[.NET]] 2.0 |
'''Platform:''' [[.NET]] 2.0 |
||
< |
<syntaxhighlight lang=csharp>Dictionary<string, string> map = new Dictionary<string,string>(); |
||
map[ "key1" ] = "foo";</ |
map[ "key1" ] = "foo";</syntaxhighlight> |
||
{{works with|C sharp|C#|3.0+}} |
{{works with|C sharp|C#|3.0+}} |
||
< |
<syntaxhighlight lang=csharp>var map = new Dictionary<string, string> {{"key1", "foo"}};</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
The C++ standard defines std::map as a means of creating an association between a key of one arbitrary type and a value of another arbitrary type. This requires the inclusion of the standard header '''map'''. |
The C++ standard defines std::map as a means of creating an association between a key of one arbitrary type and a value of another arbitrary type. This requires the inclusion of the standard header '''map'''. |
||
<lang |
<syntaxhighlight lang=cpp>#include <map></syntaxhighlight> |
||
===Creation=== |
===Creation=== |
||
To create a simple map whose key is of type A and whose value is of type B, one would define the variable like so: |
To create a simple map whose key is of type A and whose value is of type B, one would define the variable like so: |
||
< |
<syntaxhighlight lang=cpp>std::map<A, B> exampleMap</syntaxhighlight> |
||
If one wanted to us a key type of '''int''' and a value of '''double''', you would define it like so: |
If one wanted to us a key type of '''int''' and a value of '''double''', you would define it like so: |
||
< |
<syntaxhighlight lang=cpp>std::map<int, double> exampleMap</syntaxhighlight> |
||
===Insertion=== |
===Insertion=== |
||
Line 2,339: | Line 2,339: | ||
====Operator[]==== |
====Operator[]==== |
||
The first method is using the [] operator. |
The first method is using the [] operator. |
||
< |
<syntaxhighlight lang=cpp>exampleMap[7] = 3.14</syntaxhighlight> |
||
Of course, you can use a variable (or any [[rvalue]] of the correct type) for the key or value parameters: |
Of course, you can use a variable (or any [[rvalue]] of the correct type) for the key or value parameters: |
||
< |
<syntaxhighlight lang=cpp>int myKey = 7; |
||
double myValue = 3.14; |
double myValue = 3.14; |
||
exampleMap[myKey] = myValue;</ |
exampleMap[myKey] = myValue;</syntaxhighlight> |
||
====insert()==== |
====insert()==== |
||
The second approach is a little more complicated. We have to use the '''pair<>''' template: |
The second approach is a little more complicated. We have to use the '''pair<>''' template: |
||
< |
<syntaxhighlight lang=cpp>exampleMap.insert(std::pair<int, double>(7,3.14));</syntaxhighlight> |
||
or by using '''make_pair''' to avoid repeating key/value types: |
or by using '''make_pair''' to avoid repeating key/value types: |
||
< |
<syntaxhighlight lang=cpp>exampleMap.insert(std::make_pair(7,3.14));</syntaxhighlight> |
||
===Lookup=== |
===Lookup=== |
||
Line 2,355: | Line 2,355: | ||
====operator[]==== |
====operator[]==== |
||
We use it as an rvalue, supplying the correct key: |
We use it as an rvalue, supplying the correct key: |
||
< |
<syntaxhighlight lang=cpp>myValue = exampleMap[myKey]</syntaxhighlight> |
||
If the value doesn't already exist, a default-constructed object of the value's type will be inserted using the key you specified, and that default value will be returned. |
If the value doesn't already exist, a default-constructed object of the value's type will be inserted using the key you specified, and that default value will be returned. |
||
====find()==== |
====find()==== |
||
Alternatively, you can look up a value by using find(), storing its return value in an [[iterator]], and comparing the iterator against the map's end() [[sentinal value]]: |
Alternatively, you can look up a value by using find(), storing its return value in an [[iterator]], and comparing the iterator against the map's end() [[sentinal value]]: |
||
< |
<syntaxhighlight lang=cpp>double myValue = 0.0; |
||
std::map<int, double>::iterator myIterator = exampleMap.find(myKey); |
std::map<int, double>::iterator myIterator = exampleMap.find(myKey); |
||
if(exampleMap.end() != myIterator) |
if(exampleMap.end() != myIterator) |
||
Line 2,366: | Line 2,366: | ||
// Return the value for that key. |
// Return the value for that key. |
||
myValue = myIterator->second; |
myValue = myIterator->second; |
||
}</ |
}</syntaxhighlight> |
||
The need for the '''->second''' code is because our iterator points to a '''pair<>()''', and our value is the second member of that pair. |
The need for the '''->second''' code is because our iterator points to a '''pair<>()''', and our value is the second member of that pair. |
||
Line 2,374: | Line 2,374: | ||
===Example=== |
===Example=== |
||
This simple program creates a map, assigns a value to that map, retrieves a value from that map, and prints the value to STDOUT. |
This simple program creates a map, assigns a value to that map, retrieves a value from that map, and prints the value to STDOUT. |
||
< |
<syntaxhighlight lang=cpp>#include <map> |
||
#include <iostreams> |
#include <iostreams> |
||
Line 2,399: | Line 2,399: | ||
// main() must return 0 on success. |
// main() must return 0 on success. |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ceylon}}== |
=={{header|Ceylon}}== |
||
< |
<syntaxhighlight lang=ceylon>import ceylon.collection { |
||
ArrayList, |
ArrayList, |
||
Line 2,437: | Line 2,437: | ||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Chapel}}== |
=={{header|Chapel}}== |
||
Line 2,472: | Line 2,472: | ||
writeln("arr2 keys: ", arr2.domain); |
writeln("arr2 keys: ", arr2.domain); |
||
writeln("arr2 values: ", arr2);</ |
writeln("arr2 values: ", arr2);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,483: | Line 2,483: | ||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang=lisp>{:key "value" |
||
:key2 "value2" |
:key2 "value2" |
||
:key3 "value3"}</ |
:key3 "value3"}</syntaxhighlight> |
||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
< |
<syntaxhighlight lang=cfm><cfset myHash = structNew()> |
||
<cfset myHash.key1 = "foo"> |
<cfset myHash.key1 = "foo"> |
||
<cfset myHash["key2"] = "bar"> |
<cfset myHash["key2"] = "bar"> |
||
<cfset myHash.put("key3","java-style")></ |
<cfset myHash.put("key3","java-style")></syntaxhighlight> |
||
In ColdFusion, a map is literally a java.util.HashMap, thus the above 3rd method is possible. |
In ColdFusion, a map is literally a java.util.HashMap, thus the above 3rd method is possible. |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang=lisp>;; default :test is #'eql, which is suitable for numbers only, |
||
;; or for implementation identity for other types! |
;; or for implementation identity for other types! |
||
;; Use #'equalp if you want case-insensitive keying on strings. |
;; Use #'equalp if you want case-insensitive keying on strings. |
||
Line 2,508: | Line 2,508: | ||
;; alist is written like this: |
;; alist is written like this: |
||
(defparameter *legs* '((cow . 4) (flamingo . 2) (centipede . 100))) |
(defparameter *legs* '((cow . 4) (flamingo . 2) (centipede . 100))) |
||
;; you can use assoc to do lookups and cons new elements onto it to make it longer.</ |
;; you can use assoc to do lookups and cons new elements onto it to make it longer.</syntaxhighlight> |
||
=={{header|Component Pascal}}== |
=={{header|Component Pascal}}== |
||
BlackBox Componente Builder<br/> |
BlackBox Componente Builder<br/> |
||
Using a handmade collections module with the following interface<br/> |
Using a handmade collections module with the following interface<br/> |
||
< |
<syntaxhighlight lang=oberon2> |
||
DEFINITION Collections; |
DEFINITION Collections; |
||
Line 2,581: | Line 2,581: | ||
END Collections. |
END Collections. |
||
</syntaxhighlight> |
|||
</lang> |
|||
The program: |
The program: |
||
< |
<syntaxhighlight lang=oberon2> |
||
MODULE BbtAssociativeArrays; |
MODULE BbtAssociativeArrays; |
||
IMPORT StdLog, Collections, Boxes; |
IMPORT StdLog, Collections, Boxes; |
||
Line 2,606: | Line 2,606: | ||
END BbtAssociativeArrays. |
END BbtAssociativeArrays. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Execute:^Q BbtAssociativeArrays.Do<br/> |
Execute:^Q BbtAssociativeArrays.Do<br/> |
||
{{out}} |
{{out}} |
||
Line 2,614: | Line 2,614: | ||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
< |
<syntaxhighlight lang=ruby>hash1 = {"foo" => "bar"} |
||
# hash literals that don't perfectly match the intended hash type must be given an explicit type specification |
# hash literals that don't perfectly match the intended hash type must be given an explicit type specification |
||
# the following would fail without `of String => String|Int32` |
# the following would fail without `of String => String|Int32` |
||
hash2 : Hash(String, String|Int32) = {"foo" => "bar"} of String => String|Int32</ |
hash2 : Hash(String, String|Int32) = {"foo" => "bar"} of String => String|Int32</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang=d>void main() { |
||
auto hash = ["foo":42, "bar":100]; |
auto hash = ["foo":42, "bar":100]; |
||
assert("foo" in hash); |
assert("foo" in hash); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Dao}}== |
=={{header|Dao}}== |
||
< |
<syntaxhighlight lang=dao>m = { => } # empty ordered map, future inserted keys will be ordered |
||
h = { -> } # empty hash map, future inserted keys will not be ordered |
h = { -> } # empty hash map, future inserted keys will not be ordered |
||
m = { 'foo' => 42, 'bar' => 100 } # with ordered keys |
m = { 'foo' => 42, 'bar' => 100 } # with ordered keys |
||
h = { 'foo' -> 42, 'bar' -> 100 } # with unordered keys</ |
h = { 'foo' -> 42, 'bar' -> 100 } # with unordered keys</syntaxhighlight> |
||
=={{header|Dart}}== |
=={{header|Dart}}== |
||
< |
<syntaxhighlight lang=javascript> |
||
main() { |
main() { |
||
var rosettaCode = { // Type is inferred to be Map<String, String> |
var rosettaCode = { // Type is inferred to be Map<String, String> |
||
Line 2,670: | Line 2,670: | ||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,687: | Line 2,687: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
< |
<syntaxhighlight lang=Delphi>program AssociativeArrayCreation; |
||
{$APPTYPE CONSOLE} |
{$APPTYPE CONSOLE} |
||
Line 2,705: | Line 2,705: | ||
lDictionary.Free; |
lDictionary.Free; |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Diego}}== |
=={{header|Diego}}== |
||
Line 2,711: | Line 2,711: | ||
To create a dictionary associative array: |
To create a dictionary associative array: |
||
< |
<syntaxhighlight lang=diego>use_namespace(rosettacode)_me(); |
||
add_dict(tanzanianBanknoteObverseDipiction)_keys(500,1000,2000,5000,10000)_values(Karume,Nyerere,lion,black rhinoceros,elephant); |
add_dict(tanzanianBanknoteObverseDipiction)_keys(500,1000,2000,5000,10000)_values(Karume,Nyerere,lion,black rhinoceros,elephant); |
||
reset_ns[];</ |
reset_ns[];</syntaxhighlight> |
||
To create a hash associative array: |
To create a hash associative array: |
||
< |
<syntaxhighlight lang=diego>use_namespace(rosettacode)_me(); |
||
add_hash(tanzanianBanknoteReverseDipiction)_values( |
add_hash(tanzanianBanknoteReverseDipiction)_values( |
||
Line 2,728: | Line 2,728: | ||
); |
); |
||
reset_ns[];</ |
reset_ns[];</syntaxhighlight> |
||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
Line 2,734: | Line 2,734: | ||
Dyalect has a <code>Tuple</code> data type which allows to add labels to values: |
Dyalect has a <code>Tuple</code> data type which allows to add labels to values: |
||
< |
<syntaxhighlight lang=dyalect>var t = (x: 1, y: 2, z: 3) |
||
print(t.Keys().ToArray())</ |
print(t.Keys().ToArray())</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,742: | Line 2,742: | ||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang=e>[].asMap() # immutable, empty |
||
["one" => 1, "two" => 2] # immutable, 2 mappings |
["one" => 1, "two" => 2] # immutable, 2 mappings |
||
[].asMap().diverge() # mutable, empty |
[].asMap().diverge() # mutable, empty |
||
["one" => 2].diverge(String, float64) # mutable, initial contents, |
["one" => 2].diverge(String, float64) # mutable, initial contents, |
||
# typed (coerces to float)</ |
# typed (coerces to float)</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
< |
<syntaxhighlight lang=scheme> |
||
(lib 'hash) ;; needs hash.lib |
(lib 'hash) ;; needs hash.lib |
||
(define H (make-hash)) ;; new hash table |
(define H (make-hash)) ;; new hash table |
||
Line 2,768: | Line 2,768: | ||
(hash-count H) |
(hash-count H) |
||
→ 3 |
→ 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 5.0: |
ELENA 5.0: |
||
< |
<syntaxhighlight lang=elena>import system'collections; |
||
public program() |
public program() |
||
Line 2,783: | Line 2,783: | ||
map["key3"]:= "foo3"; |
map["key3"]:= "foo3"; |
||
map["key4"]:= "foo4"; |
map["key4"]:= "foo4"; |
||
}</ |
}</syntaxhighlight> |
||
=== Strong typed dictionary === |
=== Strong typed dictionary === |
||
< |
<syntaxhighlight lang=elena>import system'collections; |
||
public program() |
public program() |
||
Line 2,797: | Line 2,797: | ||
map["key3"]:= "foo3"; |
map["key3"]:= "foo3"; |
||
map["key4"]:= "foo4"; |
map["key4"]:= "foo4"; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
{{trans|Erlang}} |
{{trans|Erlang}} |
||
< |
<syntaxhighlight lang=elixir>defmodule RC do |
||
def test_create do |
def test_create do |
||
IO.puts "< create Map.new >" |
IO.puts "< create Map.new >" |
||
Line 2,817: | Line 2,817: | ||
end |
end |
||
RC.test_create</ |
RC.test_create</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,831: | Line 2,831: | ||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
< |
<syntaxhighlight lang=Lisp>(setq my-table (make-hash-table)) |
||
(puthash 'key 'value my-table)</ |
(puthash 'key 'value my-table)</syntaxhighlight> |
||
<code>make-hash-table</code> compares keys with <code>eql</code> by default. This suits symbols and numbers (including floating point). For string keys an <code>equal</code> test can be used, |
<code>make-hash-table</code> compares keys with <code>eql</code> by default. This suits symbols and numbers (including floating point). For string keys an <code>equal</code> test can be used, |
||
< |
<syntaxhighlight lang=Lisp>(setq my-table (make-hash-table :test 'equal)) |
||
(puthash "key" 123 my-table)</ |
(puthash "key" 123 my-table)</syntaxhighlight> |
||
<code>define-hash-table-test</code> can create other key comparison types. |
<code>define-hash-table-test</code> can create other key comparison types. |
||
Line 2,843: | Line 2,843: | ||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Erlang offers several associative array type data structures, this example uses the dictionary data structure. |
Erlang offers several associative array type data structures, this example uses the dictionary data structure. |
||
< |
<syntaxhighlight lang=erlang> |
||
-module(assoc). |
-module(assoc). |
||
-compile([export_all]). |
-compile([export_all]). |
||
Line 2,858: | Line 2,858: | ||
io:format("~p: ~b~n",[K,dict:fetch(K,D)]) |
io:format("~p: ~b~n",[K,dict:fetch(K,D)]) |
||
end, dict:fetch_keys(D)). |
end, dict:fetch_keys(D)). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 2,870: | Line 2,870: | ||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
.NET 3.5 Generic Dictionary (mutable) |
.NET 3.5 Generic Dictionary (mutable) |
||
< |
<syntaxhighlight lang=fsharp> |
||
let dic = System.Collections.Generic.Dictionary<string,string>() ;; |
let dic = System.Collections.Generic.Dictionary<string,string>() ;; |
||
dic.Add("key","val") ; |
dic.Add("key","val") ; |
||
dic.["key"] <- "new val" ; |
dic.["key"] <- "new val" ; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Functional dictionary (immutable) |
Functional dictionary (immutable) |
||
< |
<syntaxhighlight lang=fsharp> |
||
let d = [("key","val");("other key","other val")] |> Map.ofList |
let d = [("key","val");("other key","other val")] |> Map.ofList |
||
let newd = d.Add("new key","new val") |
let newd = d.Add("new key","new val") |
||
Line 2,884: | Line 2,884: | ||
| Some(v) -> printfn "%s" v |
| Some(v) -> printfn "%s" v |
||
| None -> printfn "not found" |
| None -> printfn "not found" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
Associative mappings follow the associative protocol. See [http://docs.factorcode.org/content/article-assocs-protocol.html the docs]. |
Associative mappings follow the associative protocol. See [http://docs.factorcode.org/content/article-assocs-protocol.html the docs]. |
||
Here's an example using a hashtable that can be run in the listener : |
Here's an example using a hashtable that can be run in the listener : |
||
< |
<syntaxhighlight lang=factor>H{ { "one" 1 } { "two" 2 } } |
||
{ [ "one" swap at . ] |
{ [ "one" swap at . ] |
||
[ 2 swap value-at . ] |
[ 2 swap value-at . ] |
||
[ "three" swap at . ] |
[ "three" swap at . ] |
||
[ [ 3 "three" ] dip set-at ] |
[ [ 3 "three" ] dip set-at ] |
||
[ "three" swap at . ] } cleave</ |
[ "three" swap at . ] } cleave</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
Line 2,900: | Line 2,900: | ||
Associative arrays are called 'maps' in Fantom: |
Associative arrays are called 'maps' in Fantom: |
||
< |
<syntaxhighlight lang=fantom> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 2,918: | Line 2,918: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
Line 2,925: | Line 2,925: | ||
The Forth dictionary is normally only used for function and symbol definitions, but you can also define separate ''wordlists'' for holding functions or data. There is no special syntax in the language for this, but you can define your own. All of Forth's defining words are available for adding things to the wordlist, but CREATE is most generic. |
The Forth dictionary is normally only used for function and symbol definitions, but you can also define separate ''wordlists'' for holding functions or data. There is no special syntax in the language for this, but you can define your own. All of Forth's defining words are available for adding things to the wordlist, but CREATE is most generic. |
||
< |
<syntaxhighlight lang=forth>: get ( key len table -- data ) \ 0 if not present |
||
search-wordlist if |
search-wordlist if |
||
>body @ |
>body @ |
||
Line 2,945: | Line 2,945: | ||
s" alpha" bar get . \ 5 |
s" alpha" bar get . \ 5 |
||
8 s" Alpha" bar put \ Forth dictionaries are normally case-insensitive |
8 s" Alpha" bar put \ Forth dictionaries are normally case-insensitive |
||
s" alpha" bar get . \ 8</ |
s" alpha" bar get . \ 8</syntaxhighlight> |
||
This is not necessarily a good option in all Forths, as the dictionary may be implemented as a simple linked list (normally not a problem because the dictionary is only used for compiling and interactive interpretation). [[GNU Forth]] and many other hosted Forths use hash tables for the dictionary, so this is a fine choice. If you need case-sensitive keys, GNU Forth has <tt>table</tt> and <tt>table-find</tt>, replacing <tt>wordlist</tt> and <tt>search-wordlist</tt>, respectively. |
This is not necessarily a good option in all Forths, as the dictionary may be implemented as a simple linked list (normally not a problem because the dictionary is only used for compiling and interactive interpretation). [[GNU Forth]] and many other hosted Forths use hash tables for the dictionary, so this is a fine choice. If you need case-sensitive keys, GNU Forth has <tt>table</tt> and <tt>table-find</tt>, replacing <tt>wordlist</tt> and <tt>search-wordlist</tt>, respectively. |
||
Line 2,953: | Line 2,953: | ||
Hashtable for mapping strings to integer |
Hashtable for mapping strings to integer |
||
< |
<syntaxhighlight lang=forth>include ffl/hct.fs |
||
\ Create a hash table 'table' in the dictionary with a starting size of 10 |
\ Create a hash table 'table' in the dictionary with a starting size of 10 |
||
Line 2,971: | Line 2,971: | ||
[ELSE] |
[ELSE] |
||
.( Entry not present.) cr |
.( Entry not present.) cr |
||
[THEN]</ |
[THEN]</syntaxhighlight> |
||
{{works with|4tH|3.64}} |
{{works with|4tH|3.64}} |
||
Line 2,998: | Line 2,998: | ||
.( Value: ) . cr |
.( Value: ) . cr |
||
then |
then |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
Uses unions to store the keys and associated values, and FreeBASIC's ability to resize arrays makes adding new entries easy. |
Uses unions to store the keys and associated values, and FreeBASIC's ability to resize arrays makes adding new entries easy. |
||
< |
<syntaxhighlight lang=freebasic>#define max(a, b) Iif(a>b,a,b) |
||
enum datatype |
enum datatype |
||
Line 3,070: | Line 3,070: | ||
print Dictionary(0).value.value.strng |
print Dictionary(0).value.value.strng |
||
print Dictionary(1).key.value.integ</ |
print Dictionary(1).key.value.integ</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 3,079: | Line 3,079: | ||
=={{header|Free Pascal}}== |
=={{header|Free Pascal}}== |
||
FPC 3.2.0.+. Similar to Delphi. |
FPC 3.2.0.+. Similar to Delphi. |
||
< |
<syntaxhighlight lang=pascal>program AssociativeArrayCreation; |
||
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF} |
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF} |
||
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF} |
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF} |
||
Line 3,095: | Line 3,095: | ||
lDictionary.Free; |
lDictionary.Free; |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
FPC 2.4+. Using FGL instead of rtl-generics: |
FPC 2.4+. Using FGL instead of rtl-generics: |
||
< |
<syntaxhighlight lang=pascal>program AssociativeArrayCreation; |
||
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF} |
{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF} |
||
{$MODE DELPHI} |
{$MODE DELPHI} |
||
Line 3,113: | Line 3,113: | ||
lDictionary.Free; |
lDictionary.Free; |
||
end; |
end; |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Futhark}}== |
=={{header|Futhark}}== |
||
< |
<syntaxhighlight lang=futhark>let associative_array = {key1=1,key2=2}</syntaxhighlight> |
||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
Line 3,123: | Line 3,123: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
Allowable key types are those with == and != operators. This includes is boolean, numeric, string, pointer, channel, and interface types. It also includes structs and arrays containing only these types. Disallowed as map keys are all slice, function, and map types. |
Allowable key types are those with == and != operators. This includes is boolean, numeric, string, pointer, channel, and interface types. It also includes structs and arrays containing only these types. Disallowed as map keys are all slice, function, and map types. |
||
< |
<syntaxhighlight lang=go>// declare a nil map variable, for maps from string to int |
||
var x map[string]int |
var x map[string]int |
||
Line 3,145: | Line 3,145: | ||
x = map[string]int{ |
x = map[string]int{ |
||
"foo": 2, "bar": 42, "baz": -1, |
"foo": 2, "bar": 42, "baz": -1, |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Gosu}}== |
=={{header|Gosu}}== |
||
As an OOP language with generics Gosu can use any variety of Map classes. In addition Gosu provides associative array syntax for all objects. |
As an OOP language with generics Gosu can use any variety of Map classes. In addition Gosu provides associative array syntax for all objects. |
||
< |
<syntaxhighlight lang=javascript>// empty map |
||
var emptyMap = new HashMap<String, Integer>() |
var emptyMap = new HashMap<String, Integer>() |
||
Line 3,183: | Line 3,183: | ||
var scott = new Person() |
var scott = new Person() |
||
scott["name"] = "Scott" |
scott["name"] = "Scott" |
||
scott["age"] = 29</ |
scott["age"] = 29</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Create an empty map and add values |
Create an empty map and add values |
||
< |
<syntaxhighlight lang=groovy>map = [:] |
||
map[7] = 7 |
map[7] = 7 |
||
map['foo'] = 'foovalue' |
map['foo'] = 'foovalue' |
||
Line 3,196: | Line 3,196: | ||
assert 'foovalue' == map.foo |
assert 'foovalue' == map.foo |
||
assert 'barvalue' == map['bar'] |
assert 'barvalue' == map['bar'] |
||
assert 'moovalue' == map.get('moo')</ |
assert 'moovalue' == map.get('moo')</syntaxhighlight> |
||
Create a pre-populated map and verify values |
Create a pre-populated map and verify values |
||
< |
<syntaxhighlight lang=groovy>map = [7:7, foo:'foovalue', bar:'barvalue', moo:'moovalue'] |
||
assert 7 == map[7] |
assert 7 == map[7] |
||
assert 'foovalue' == map.foo |
assert 'foovalue' == map.foo |
||
assert 'barvalue' == map['bar'] |
assert 'barvalue' == map['bar'] |
||
assert 'moovalue' == map.get('moo')</ |
assert 'moovalue' == map.get('moo')</syntaxhighlight> |
||
=={{header|Harbour}}== |
=={{header|Harbour}}== |
||
Create an empty array and add values: |
Create an empty array and add values: |
||
< |
<syntaxhighlight lang=visualfoxpro>arr := { => } |
||
arr[ 10 ] := "Val_10" |
arr[ 10 ] := "Val_10" |
||
arr[ "foo" ] := "foovalue"</ |
arr[ "foo" ] := "foovalue"</syntaxhighlight> |
||
Create and initialize array: |
Create and initialize array: |
||
< |
<syntaxhighlight lang=visualfoxpro>arr := hb_Hash( 10, "Val_10", "foo", "foovalue" ) |
||
// or |
// or |
||
arr := { 10 => "Val_10", "foo" => "foovalue" }</ |
arr := { 10 => "Val_10", "foo" => "foovalue" }</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Binary trees: |
Binary trees: |
||
{{works with|GHC}} |
{{works with|GHC}} |
||
< |
<syntaxhighlight lang=haskell>import Data.Map |
||
dict = fromList [("key1","val1"), ("key2","val2")] |
dict = fromList [("key1","val1"), ("key2","val2")] |
||
ans = Data.Map.lookup "key2" dict -- evaluates to Just "val2" |
ans = Data.Map.lookup "key2" dict -- evaluates to Just "val2" |
||
</syntaxhighlight> |
|||
</lang> |
|||
It is also possible to use association lists (lists of pairs). It is inefficient (O(n) lookup), but simple. |
It is also possible to use association lists (lists of pairs). It is inefficient (O(n) lookup), but simple. |
||
< |
<syntaxhighlight lang=haskell>dict = [("key1","val1"), ("key2","val2")] |
||
ans = lookup "key2" dict -- evaluates to Just "val2" |
ans = lookup "key2" dict -- evaluates to Just "val2" |
||
</syntaxhighlight> |
|||
</lang> |
|||
GHC also had an imperative hash table implementation in the <code>Data.HashTable</code> module, but was removed in <code>GHC 7.8</code>. |
GHC also had an imperative hash table implementation in the <code>Data.HashTable</code> module, but was removed in <code>GHC 7.8</code>. |
||
Line 3,237: | Line 3,237: | ||
=={{header|hexiscript}}== |
=={{header|hexiscript}}== |
||
< |
<syntaxhighlight lang=hexiscript>let d dict 2 # Initial estimated size |
||
let d["test"] "test" # Strings can be used as index |
let d["test"] "test" # Strings can be used as index |
||
let d[123] 123 # Integers can also be used as index |
let d[123] 123 # Integers can also be used as index |
||
println d["test"] |
println d["test"] |
||
println d[123]</ |
println d[123]</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Icon and Unicon associative arrays are called tables. Any value may be used as a key including complex structures. Tables can have default values and they have no inherent size limitation growing from empty to whatever size is needed. |
Icon and Unicon associative arrays are called tables. Any value may be used as a key including complex structures. Tables can have default values and they have no inherent size limitation growing from empty to whatever size is needed. |
||
< |
<syntaxhighlight lang=icon>procedure main() |
||
local t |
local t |
||
t := table() |
t := table() |
||
t["foo"] := "bar" |
t["foo"] := "bar" |
||
write(t["foo"]) |
write(t["foo"]) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Inform 7}}== |
=={{header|Inform 7}}== |
||
Line 3,258: | Line 3,258: | ||
===Static relation=== |
===Static relation=== |
||
< |
<syntaxhighlight lang=inform7>Hash Bar is a room. |
||
Connection relates various texts to one number. The verb to be connected to implies the connection relation. |
Connection relates various texts to one number. The verb to be connected to implies the connection relation. |
||
Line 3,275: | Line 3,275: | ||
let V be the number that "baz" relates to by the connection relation; |
let V be the number that "baz" relates to by the connection relation; |
||
say "'baz' => [V]."; |
say "'baz' => [V]."; |
||
end the story.</ |
end the story.</syntaxhighlight> |
||
===Dynamic relation=== |
===Dynamic relation=== |
||
< |
<syntaxhighlight lang=inform7>Hash Bar is a room. |
||
When play begins: |
When play begins: |
||
Line 3,292: | Line 3,292: | ||
let V be the number that "baz" relates to by R; |
let V be the number that "baz" relates to by R; |
||
say "'baz' => [V]."; |
say "'baz' => [V]."; |
||
end the story.</ |
end the story.</syntaxhighlight> |
||
=={{header|Ioke}}== |
=={{header|Ioke}}== |
||
< |
<syntaxhighlight lang=ioke>{a: "a", b: "b"}</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 3,303: | Line 3,303: | ||
However, it's also possible to use the symbol table itself to hold the names. The symbol table has limitations (can only accept syntactically valid names), but we can turn arbitrary strings into valid symbols using base 62 encode and prefixing with a letter (hypothetically speaking, base 64 encode would let us build longer names than base 62, because of computational complexity issues - but the J symbol table also comes with a name length limit - 255 characters - and does not support 64 different characters in names): |
However, it's also possible to use the symbol table itself to hold the names. The symbol table has limitations (can only accept syntactically valid names), but we can turn arbitrary strings into valid symbols using base 62 encode and prefixing with a letter (hypothetically speaking, base 64 encode would let us build longer names than base 62, because of computational complexity issues - but the J symbol table also comes with a name length limit - 255 characters - and does not support 64 different characters in names): |
||
< |
<syntaxhighlight lang=J>coclass 'assocArray' |
||
encode=: 'z', (a.{~;48 65 97(+ i.)&.>10 26 26) {~ 62x #.inv 256x #. a.&i. |
encode=: 'z', (a.{~;48 65 97(+ i.)&.>10 26 26) {~ 62x #.inv 256x #. a.&i. |
||
get=: ".@encode |
get=: ".@encode |
||
has=: 0 <: nc@<@encode |
has=: 0 <: nc@<@encode |
||
set=:4 :'(encode x)=:y'</ |
set=:4 :'(encode x)=:y'</syntaxhighlight> |
||
Example use: |
Example use: |
||
< |
<syntaxhighlight lang=j> example=: conew 'assocArray' |
||
'foo' set__example 1 2 3 |
'foo' set__example 1 2 3 |
||
1 2 3 |
1 2 3 |
||
Line 3,323: | Line 3,323: | ||
get__example 'bletch' |
get__example 'bletch' |
||
7 8 9 |
7 8 9 |
||
codestroy__example''</ |
codestroy__example''</syntaxhighlight> |
||
Note that J's symbols (http://www.jsoftware.com/help/dictionary/dsco.htm) might also be used for this purpose. However, symbols are not garbage collected within a J session (and, instead, a mechanism is provided to optionally preserve them across sessions). |
Note that J's symbols (http://www.jsoftware.com/help/dictionary/dsco.htm) might also be used for this purpose. However, symbols are not garbage collected within a J session (and, instead, a mechanism is provided to optionally preserve them across sessions). |
||
Line 3,331: | Line 3,331: | ||
Defining the Map: |
Defining the Map: |
||
< |
<syntaxhighlight lang=java5>Map<String, Integer> map = new HashMap<String, Integer>(); |
||
map.put("foo", 5); |
map.put("foo", 5); |
||
map.put("bar", 10); |
map.put("bar", 10); |
||
map.put("baz", 15); |
map.put("baz", 15); |
||
map.put("foo", 6);</ |
map.put("foo", 6);</syntaxhighlight> |
||
"Putting" a value for a key that already exists ("map.put("foo", 6)" in this example) will replace and return the old value for the key. |
"Putting" a value for a key that already exists ("map.put("foo", 6)" in this example) will replace and return the old value for the key. |
||
Initializing a Map as a class member: |
Initializing a Map as a class member: |
||
< |
<syntaxhighlight lang=java5>public static Map<String, Integer> map = new HashMap<String, Integer>(){{ |
||
put("foo", 5); |
put("foo", 5); |
||
put("bar", 10); |
put("bar", 10); |
||
put("baz", 15); |
put("baz", 15); |
||
put("foo", 6); |
put("foo", 6); |
||
}};</ |
}};</syntaxhighlight> |
||
Retrieving a value: |
Retrieving a value: |
||
< |
<syntaxhighlight lang=java5>map.get("foo"); // => 6 |
||
map.get("invalid"); // => null</ |
map.get("invalid"); // => null</syntaxhighlight> |
||
Note that it is possible to put <code>null</code> as a value, so <code>null</code> being returned by <code>get</code> is not sufficient for determining that the key is not in the <code>Map</code>. There is a <code>containsKey</code> method for that. |
Note that it is possible to put <code>null</code> as a value, so <code>null</code> being returned by <code>get</code> is not sufficient for determining that the key is not in the <code>Map</code>. There is a <code>containsKey</code> method for that. |
||
Iterate over keys: |
Iterate over keys: |
||
< |
<syntaxhighlight lang=java5>for (String key: map.keySet()) |
||
System.out.println(key);</ |
System.out.println(key);</syntaxhighlight> |
||
Iterate over values: |
Iterate over values: |
||
< |
<syntaxhighlight lang=java5>for (int value: map.values()) |
||
System.out.println(value);</ |
System.out.println(value);</syntaxhighlight> |
||
Iterate over key, value pairs: |
Iterate over key, value pairs: |
||
< |
<syntaxhighlight lang=java5>for (Map.Entry<String, Integer> entry: map.entrySet()) |
||
System.out.println(entry.getKey() + " => " + entry.getValue());</ |
System.out.println(entry.getKey() + " => " + entry.getValue());</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 3,364: | Line 3,364: | ||
Javascript object property names (keys) are strings. Other types and expressions can be used with square bracket notation, they are evaluated and converted to strings and the result used as the property name. Using quotes on property names avoids potential collisions with reserved JavaScript key words. |
Javascript object property names (keys) are strings. Other types and expressions can be used with square bracket notation, they are evaluated and converted to strings and the result used as the property name. Using quotes on property names avoids potential collisions with reserved JavaScript key words. |
||
< |
<syntaxhighlight lang=javascript>var assoc = {}; |
||
assoc['foo'] = 'bar'; |
assoc['foo'] = 'bar'; |
||
Line 3,385: | Line 3,385: | ||
alert('key:"' + key + '", value:"' + assoc[key] + '"'); |
alert('key:"' + key + '", value:"' + assoc[key] + '"'); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
ECMAScript 6 (ES6) offers both a map and a weak map implementation. While Objects must use strings, Maps may use objects, functions, and numbers as keys in addition to strings. |
ECMAScript 6 (ES6) offers both a map and a weak map implementation. While Objects must use strings, Maps may use objects, functions, and numbers as keys in addition to strings. |
||
< |
<syntaxhighlight lang=javascript>var map = new Map(), |
||
fn = function () {}, |
fn = function () {}, |
||
obj = {}; |
obj = {}; |
||
Line 3,409: | Line 3,409: | ||
for (var key of map.keys()) { |
for (var key of map.keys()) { |
||
console.log(key + ' => ' + map.get(key)); |
console.log(key + ' => ' + map.get(key)); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
===Associative Arrays with String-Valued Keys=== |
===Associative Arrays with String-Valued Keys=== |
||
In jq, JSON objects can be used as associative arrays, it being understood that only strings can be used as keys. To avoid confusion, for the remainder of this section, we refer to JSON objects as such. Their type in jq is "object". |
In jq, JSON objects can be used as associative arrays, it being understood that only strings can be used as keys. To avoid confusion, for the remainder of this section, we refer to JSON objects as such. Their type in jq is "object". |
||
< |
<syntaxhighlight lang=jq># An empty object: |
||
{} |
{} |
||
Line 3,435: | Line 3,435: | ||
# Alteration of the value of an existing key: |
# Alteration of the value of an existing key: |
||
{"A": 65}["A"] = "AA"</ |
{"A": 65}["A"] = "AA"</syntaxhighlight> |
||
===Associative Arrays with JSON-Valued Keys=== |
===Associative Arrays with JSON-Valued Keys=== |
||
In this subsection, we define addKey(key;value), getKey(key), and removeKey(key) |
In this subsection, we define addKey(key;value), getKey(key), and removeKey(key) |
||
to operate on a hash table for which the keys may be any JSON entities. This is done by defining a collisionless hash function. |
to operate on a hash table for which the keys may be any JSON entities. This is done by defining a collisionless hash function. |
||
< |
<syntaxhighlight lang=jq>def collisionless: |
||
if type == "object" then with_entries(.value = (.value|collisionless))|tostring |
if type == "object" then with_entries(.value = (.value|collisionless))|tostring |
||
elif type == "array" then map(collisionless)|tostring |
elif type == "array" then map(collisionless)|tostring |
||
Line 3,454: | Line 3,454: | ||
def getKey(key): .[key|collisionless]; |
def getKey(key): .[key|collisionless]; |
||
def removeKey(key): delpaths( [ [key|collisionless] ] );</ |
def removeKey(key): delpaths( [ [key|collisionless] ] );</syntaxhighlight> |
||
'''Example''': |
'''Example''': |
||
< |
<syntaxhighlight lang=jq>{} | addKey(1;"one") | addKey(2; "two") | removeKey(1) | getKey(2)</syntaxhighlight> |
||
produces: |
produces: |
||
<lang |
<syntaxhighlight lang=sh>"two"</syntaxhighlight> |
||
=={{header|Jsish}}== |
=={{header|Jsish}}== |
||
From Javascript. jsish warns of duplicate ''var'', in this case the ''assoc'' variable is reused. |
From Javascript. jsish warns of duplicate ''var'', in this case the ''assoc'' variable is reused. |
||
< |
<syntaxhighlight lang=javascript>var assoc = {}; |
||
assoc['foo'] = 'bar'; |
assoc['foo'] = 'bar'; |
||
Line 3,495: | Line 3,495: | ||
assoc ==> { "another-key":3, foo:"bar" } |
assoc ==> { "another-key":3, foo:"bar" } |
||
=!EXPECTEND!= |
=!EXPECTEND!= |
||
*/</ |
*/</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>prompt$ jsish -u associativeArray.jsi |
<pre>prompt$ jsish -u associativeArray.jsi |
||
Line 3,503: | Line 3,503: | ||
{{works with|Julia|0.6}} |
{{works with|Julia|0.6}} |
||
We build dictionaries associating to some characters their code points, by listing the key/value pairs, through a dictionary comprehension, by creating an empty dictionary and filling it, by using the specific syntax associated to typed dictionaries. |
We build dictionaries associating to some characters their code points, by listing the key/value pairs, through a dictionary comprehension, by creating an empty dictionary and filling it, by using the specific syntax associated to typed dictionaries. |
||
< |
<syntaxhighlight lang=julia>dict = Dict('a' => 97, 'b' => 98) # list keys/values |
||
# Dict{Char,Int64} with 2 entries: |
# Dict{Char,Int64} with 2 entries: |
||
# 'b' => 98 |
# 'b' => 98 |
||
Line 3,529: | Line 3,529: | ||
typeof(dict) # type is infered correctly |
typeof(dict) # type is infered correctly |
||
# Dict{Char,Int64} |
# Dict{Char,Int64} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|K}}== |
=={{header|K}}== |
||
Keys in a dictionary must be symbols (`symbol). |
Keys in a dictionary must be symbols (`symbol). |
||
< |
<syntaxhighlight lang=K> / creating an dictionary |
||
d1:.((`foo;1); (`bar;2); (`baz;3)) |
d1:.((`foo;1); (`bar;2); (`baz;3)) |
||
/ extracting a value |
/ extracting a value |
||
d1[`bar] |
d1[`bar] |
||
2</ |
2</syntaxhighlight> |
||
Another approach. |
Another approach. |
||
< |
<syntaxhighlight lang=K> d2: .() / create empty dictionary |
||
d2[`"zero"]:0 |
d2[`"zero"]:0 |
||
d2[`"one"]:1 |
d2[`"one"]:1 |
||
Line 3,549: | Line 3,549: | ||
.((`zero;0;) |
.((`zero;0;) |
||
(`one;1;) |
(`one;1;) |
||
(`two;2;))</ |
(`two;2;))</syntaxhighlight> |
||
Extracting the keys and values. |
Extracting the keys and values. |
||
< |
<syntaxhighlight lang=K> !d2 / the keys |
||
`zero `one `two |
`zero `one `two |
||
d2[] / the values |
d2[] / the values |
||
0 1 2</ |
0 1 2</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
< |
<syntaxhighlight lang=scala>fun main(args: Array<String>) { |
||
// map definition: |
// map definition: |
||
val map = mapOf("foo" to 5, |
val map = mapOf("foo" to 5, |
||
Line 3,585: | Line 3,585: | ||
// iterate over key, value pairs: |
// iterate over key, value pairs: |
||
for ((k, v) in map) println("$k => $v") |
for ((k, v) in map) println("$k => $v") |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
Associative arrays are not currently built in the JS.js kernel of lambdatalk but are added via the lib_hash library page. |
Associative arrays are not currently built in the JS.js kernel of lambdatalk but are added via the lib_hash library page. |
||
< |
<syntaxhighlight lang=scheme> |
||
1) a (currently) reduced set of functions: |
1) a (currently) reduced set of functions: |
||
Line 3,647: | Line 3,647: | ||
bar: Barcelona, Catalunya |
bar: Barcelona, Catalunya |
||
] |
] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lang5}}== |
=={{header|Lang5}}== |
||
< |
<syntaxhighlight lang=lang5>: dip swap '_ set execute _ ; : nip swap drop ; |
||
: first 0 extract nip ; : second 1 extract nip ; |
: first 0 extract nip ; : second 1 extract nip ; |
||
Line 3,666: | Line 3,666: | ||
'bar over at . |
'bar over at . |
||
'hello 'bar rot set-at |
'hello 'bar rot set-at |
||
20 'baz rot set-at .</ |
20 'baz rot set-at .</syntaxhighlight> |
||
=={{header|langur}}== |
=={{header|langur}}== |
||
Hash keys in langur may be numbers or strings. Number keys are simplified, so that 1.0 is the same key as 1. |
Hash keys in langur may be numbers or strings. Number keys are simplified, so that 1.0 is the same key as 1. |
||
< |
<syntaxhighlight lang=langur>var .hash = h{1: "abc", "1": 789} |
||
# may assign with existing or non-existing hash key (if hash is mutable) |
# may assign with existing or non-existing hash key (if hash is mutable) |
||
Line 3,682: | Line 3,682: | ||
# using an alternate value in case of invalid index; prevents exception |
# using an alternate value in case of invalid index; prevents exception |
||
writeln .hash[1; 42] |
writeln .hash[1; 42] |
||
writeln .hash[2; 42]</ |
writeln .hash[2; 42]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,692: | Line 3,692: | ||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang=Lasso>// In Lasso associative arrays are called maps |
||
// Define an empty map |
// Define an empty map |
||
Line 3,729: | Line 3,729: | ||
#1 -> reverse |
#1 -> reverse |
||
} |
} |
||
#mymap // map(2 = YADSEUT, fourth = YADSRUHT, one = YADNOM, 3 = YADSENDEW)</ |
#mymap // map(2 = YADSEUT, fourth = YADSRUHT, one = YADNOM, 3 = YADSENDEW)</syntaxhighlight> |
||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
< |
<syntaxhighlight lang=lisp> |
||
(let* ((my-dict (: dict new)) |
(let* ((my-dict (: dict new)) |
||
(my-dict (: dict store 'key-1 '"value 1" my-dict)) |
(my-dict (: dict store 'key-1 '"value 1" my-dict)) |
||
Line 3,739: | Line 3,739: | ||
(: io format '"some data: ~p~n" (list (: dict fetch 'key-1 my-dict)))) |
(: io format '"some data: ~p~n" (list (: dict fetch 'key-1 my-dict)))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
Needs the sublist library from http://basic.wikispaces.com/SubList+Library since LB does not have built-in associative arrays. |
Needs the sublist library from http://basic.wikispaces.com/SubList+Library since LB does not have built-in associative arrays. |
||
<syntaxhighlight lang=lb> |
|||
<lang lb> |
|||
data "red", "255 50 50", "green", "50 255 50", "blue", "50 50 255" |
data "red", "255 50 50", "green", "50 255 50", "blue", "50 50 255" |
||
data "my fave", "220 120 120", "black", "0 0 0" |
data "my fave", "220 120 120", "black", "0 0 0" |
||
Line 3,756: | Line 3,756: | ||
print " Key 'green' is associated with data item "; sl.Get$( myAssocList$, "green") |
print " Key 'green' is associated with data item "; sl.Get$( myAssocList$, "green") |
||
</syntaxhighlight> |
|||
</lang> |
|||
Key 'green' is associated with data item 50 255 50 |
Key 'green' is associated with data item 50 255 50 |
||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
< |
<syntaxhighlight lang=lingo>props = [#key1: "value1", #key2: "value2"] |
||
put props[#key2] |
put props[#key2] |
||
Line 3,769: | Line 3,769: | ||
-- "value2" |
-- "value2" |
||
put props.getProp(#key2) |
put props.getProp(#key2) |
||
-- "value2"</ |
-- "value2"</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
Livecode arrays are only associative, but can be accessed by ordinal if they are used as the key. |
Livecode arrays are only associative, but can be accessed by ordinal if they are used as the key. |
||
< |
<syntaxhighlight lang=LiveCode>command assocArray |
||
local tArray |
local tArray |
||
put "value 1" into tArray["key 1"] |
put "value 1" into tArray["key 1"] |
||
Line 3,782: | Line 3,782: | ||
"length of item 3:" && the length of tArray["abc"] & return & \ |
"length of item 3:" && the length of tArray["abc"] & return & \ |
||
"keys:" && the keys of tArray |
"keys:" && the keys of tArray |
||
end assocArray</ |
end assocArray</syntaxhighlight> |
||
Output |
Output |
||
< |
<syntaxhighlight lang=LiveCode>number of elements: 3 |
||
length of item 3: 5 |
length of item 3: 5 |
||
keys: key numbers |
keys: key numbers |
||
abc |
abc |
||
key 1</ |
key 1</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
[[UCB Logo]] has "property lists" which associate names with values. They have their own namespace. |
[[UCB Logo]] has "property lists" which associate names with values. They have their own namespace. |
||
< |
<syntaxhighlight lang=logo>pprop "animals "cat 5 |
||
pprop "animals "dog 4 |
pprop "animals "dog 4 |
||
pprop "animals "mouse 11 |
pprop "animals "mouse 11 |
||
print gprop "animals "cat ; 5 |
print gprop "animals "cat ; 5 |
||
remprop "animals "dog |
remprop "animals "dog |
||
show plist "animals ; [mouse 11 cat 5]</ |
show plist "animals ; [mouse 11 cat 5]</syntaxhighlight> |
||
=={{header|LOLCODE}}== |
=={{header|LOLCODE}}== |
||
BUKKITs are associative arrays |
BUKKITs are associative arrays |
||
< |
<syntaxhighlight lang=lolcode>HAI 1.2 |
||
I HAS A Hash ITZ A BUKKIT |
I HAS A Hash ITZ A BUKKIT |
||
Hash HAS A key1 ITZ "val1" BTW This works for identifier-like keys, like obj.key in JavaScript |
Hash HAS A key1 ITZ "val1" BTW This works for identifier-like keys, like obj.key in JavaScript |
||
Line 3,807: | Line 3,807: | ||
VISIBLE Hash'Z SRS "key-2" |
VISIBLE Hash'Z SRS "key-2" |
||
KTHXBYE |
KTHXBYE |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>1</pre> |
<pre>1</pre> |
||
Line 3,813: | Line 3,813: | ||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
Lua tables are Hashes |
Lua tables are Hashes |
||
< |
<syntaxhighlight lang=lua>hash = {} |
||
hash[ "key-1" ] = "val1" |
hash[ "key-1" ] = "val1" |
||
hash[ "key-2" ] = 1 |
hash[ "key-2" ] = 1 |
||
hash[ "key-3" ] = {}</ |
hash[ "key-3" ] = {}</syntaxhighlight> |
||
Returns nil on unknown key. |
Returns nil on unknown key. |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
Μ2000 has Inventory object to use it as a Map. All keys converted to strings. If a key has no value then key is the value until we place one. A special type of Inventory is the Inventory Queue, where we can use same keys, and we can't delete except from the last append. |
Μ2000 has Inventory object to use it as a Map. All keys converted to strings. If a key has no value then key is the value until we place one. A special type of Inventory is the Inventory Queue, where we can use same keys, and we can't delete except from the last append. |
||
< |
<syntaxhighlight lang=M2000 Interpreter> |
||
Inventory A="100":=1, "200":=5, 10:=500, 20:="Hello There" |
Inventory A="100":=1, "200":=5, 10:=500, 20:="Hello There" |
||
Print len(A) |
Print len(A) |
||
Line 3,843: | Line 3,843: | ||
If Exist(A, "End") Then Print Eval(A)=5000 |
If Exist(A, "End") Then Print Eval(A)=5000 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
Maple tables are hashed arrays. A table can be constructed by using the table constructor. |
Maple tables are hashed arrays. A table can be constructed by using the table constructor. |
||
< |
<syntaxhighlight lang=Maple>> T := table( [ (2,3) = 4, "foo" = 1, sin(x) = cos(x) ] ); |
||
T := table(["foo" = 1, sin(x) = cos(x), (2, 3) = 4]) |
T := table(["foo" = 1, sin(x) = cos(x), (2, 3) = 4]) |
||
Line 3,857: | Line 3,857: | ||
> T["foo"]; |
> T["foo"]; |
||
1</ |
1</syntaxhighlight> |
||
New entries are added by assignment. |
New entries are added by assignment. |
||
< |
<syntaxhighlight lang=Maple>> T[ "bar" ] := 2; |
||
T["bar"] := 2 |
T["bar"] := 2 |
||
> T[ "bar" ]; |
> T[ "bar" ]; |
||
2</ |
2</syntaxhighlight> |
||
Entries can be removed as follows. |
Entries can be removed as follows. |
||
< |
<syntaxhighlight lang=Maple>> T[ "foo" ] := evaln( T[ "foo" ] ); |
||
T["foo"] := T["foo"] |
T["foo"] := T["foo"] |
||
> T[ "foo" ]; |
> T[ "foo" ]; |
||
T["foo"]</ |
T["foo"]</syntaxhighlight> |
||
(The latter output indicates that T["foo"] is an unassigned name.) |
(The latter output indicates that T["foo"] is an unassigned name.) |
||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang=Mathematica>a[2] = "string"; a["sometext"] = 23;</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
Line 3,880: | Line 3,880: | ||
Associative arrays are called structs. The following methods of creating hash are equivalent. |
Associative arrays are called structs. The following methods of creating hash are equivalent. |
||
< |
<syntaxhighlight lang=MATLAB> hash.a = 1; |
||
hash.b = 2; |
hash.b = 2; |
||
hash.C = [3,4,5]; </ |
hash.C = [3,4,5]; </syntaxhighlight> |
||
alternatively |
alternatively |
||
< |
<syntaxhighlight lang=MATLAB> hash = []; |
||
hash = setfield(hash,'a',1); |
hash = setfield(hash,'a',1); |
||
hash = setfield(hash,'b',2); |
hash = setfield(hash,'b',2); |
||
hash = setfield(hash,'C',[3,4,5]); </ |
hash = setfield(hash,'C',[3,4,5]); </syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang=MATLAB> hash.('a') = 1; |
||
hash.('b') = 2; |
hash.('b') = 2; |
||
hash.('C') = [3,4,5]; </ |
hash.('C') = [3,4,5]; </syntaxhighlight> |
||
<pre>>> disp(hash) |
<pre>>> disp(hash) |
||
Line 3,905: | Line 3,905: | ||
===MATLAB only: containers.Map=== |
===MATLAB only: containers.Map=== |
||
Use of containers.Map removes some restrictions on key types that structs have. Keys can all be numeric or all be strings. Values can be of any type. Key and value types cannot be changed after creation of the containers.Map object. |
Use of containers.Map removes some restrictions on key types that structs have. Keys can all be numeric or all be strings. Values can be of any type. Key and value types cannot be changed after creation of the containers.Map object. |
||
< |
<syntaxhighlight lang=MATLAB>m = containers.Map({'a' 'b' 'C'}, [1 2 3]);</syntaxhighlight> |
||
is equivalent to |
is equivalent to |
||
< |
<syntaxhighlight lang=MATLAB>m = containers.Map; |
||
m('a') = 1; |
m('a') = 1; |
||
m('b') = 2; |
m('b') = 2; |
||
m('C') = 3;</ |
m('C') = 3;</syntaxhighlight> |
||
since the KeyType defaults to 'char'. For numeric keys, the key and value types must be specified at creation. |
since the KeyType defaults to 'char'. For numeric keys, the key and value types must be specified at creation. |
||
< |
<syntaxhighlight lang=MATLAB>m = containers.Map([51 72 37], {'fiftyone' 'seventytwo' 'thirtyseven'});</syntaxhighlight> |
||
is equivalent to |
is equivalent to |
||
< |
<syntaxhighlight lang=MATLAB>m = containers.Map('KeyType', 'double', 'ValueType', 'any'); |
||
m(51) = 'fiftyone'; |
m(51) = 'fiftyone'; |
||
m(72) = 'seventytwo'; |
m(72) = 'seventytwo'; |
||
m(37) = 'thirtyseven';</ |
m(37) = 'thirtyseven';</syntaxhighlight> |
||
Usage: |
Usage: |
||
<pre>>> m = containers.Map([51 72 37], {'fiftyone' 'seventytwo' 'thirtyseven'}); |
<pre>>> m = containers.Map([51 72 37], {'fiftyone' 'seventytwo' 'thirtyseven'}); |
||
Line 3,933: | Line 3,933: | ||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang=maxima>/* No need to declare anything, undeclared arrays are hashed */ |
||
h[1]: 6; |
h[1]: 6; |
||
Line 3,939: | Line 3,939: | ||
arrayinfo(h); |
arrayinfo(h); |
||
[hashed, 1, [1], [9]]</ |
[hashed, 1, [1], [9]]</syntaxhighlight> |
||
=={{header|min}}== |
=={{header|min}}== |
||
{{works with|min|0.19.6}} |
{{works with|min|0.19.6}} |
||
< |
<syntaxhighlight lang=min>{1 :one 2 :two 3 :three}</syntaxhighlight> |
||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
A map literal in MiniScript is enclosed in curly braces, with key:value pairs separated by commas. Keys and values may be any type. Retrieval or assignment is by putting the key in square brackets. As syntactic sugar, when a string key follows the rules of a MiniScript identifier (starts with a letter and contains only letters, numbers, and underscores), you may also access it with dot syntax. |
A map literal in MiniScript is enclosed in curly braces, with key:value pairs separated by commas. Keys and values may be any type. Retrieval or assignment is by putting the key in square brackets. As syntactic sugar, when a string key follows the rules of a MiniScript identifier (starts with a letter and contains only letters, numbers, and underscores), you may also access it with dot syntax. |
||
< |
<syntaxhighlight lang=MiniScript>map = { 3: "test", "foo": 42 } |
||
print map[3] |
print map[3] |
||
Line 3,954: | Line 3,954: | ||
print map["foo"] |
print map["foo"] |
||
print map.foo // same as map["foo"] (only for string keys that are valid identifiers) |
print map.foo // same as map["foo"] (only for string keys that are valid identifiers) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
This demonstrates two of several constructors, initializing the hashtable with a list of tuples or just specifying an initial capacity. |
This demonstrates two of several constructors, initializing the hashtable with a list of tuples or just specifying an initial capacity. |
||
< |
<syntaxhighlight lang=Nemerle>using System; |
||
using System.Console; |
using System.Console; |
||
using Nemerle.Collections; |
using Nemerle.Collections; |
||
Line 3,974: | Line 3,974: | ||
WriteLine(hash1[entry]); |
WriteLine(hash1[entry]); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang=NetRexx>/* NetRexx */ |
||
options replace format comments java crossref symbols |
options replace format comments java crossref symbols |
||
Line 3,988: | Line 3,988: | ||
say '<hash key="'key0'" value="'hash[key0]'" />' -- Display a value for a key that wasn't set |
say '<hash key="'key0'" value="'hash[key0]'" />' -- Display a value for a key that wasn't set |
||
say '<hash key="'key1'" value="'hash[key1]'" />' -- Display a value for a key that was set</ |
say '<hash key="'key1'" value="'hash[key1]'" />' -- Display a value for a key that was set</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,997: | Line 3,997: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang=nim>import tables |
||
var |
var |
||
Line 4,025: | Line 4,025: | ||
echo "iterate values:" # iterating over values |
echo "iterate values:" # iterating over values |
||
for key in hash.values: |
for key in hash.values: |
||
echo key</ |
echo key</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>hash has 3 elements |
<pre>hash has 3 elements |
||
Line 4,045: | Line 4,045: | ||
=={{header|Oberon-2}}== |
=={{header|Oberon-2}}== |
||
{{works with| oo2c Version 2}} |
{{works with| oo2c Version 2}} |
||
< |
<syntaxhighlight lang=oberon2> |
||
MODULE AssociativeArray; |
MODULE AssociativeArray; |
||
IMPORT |
IMPORT |
||
Line 4,088: | Line 4,088: | ||
END AssociativeArray. |
END AssociativeArray. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
Line 4,094: | Line 4,094: | ||
=== Associative map=== |
=== Associative map=== |
||
< |
<syntaxhighlight lang=objeck> |
||
# create map |
# create map |
||
map := StringMap->New(); |
map := StringMap->New(); |
||
Line 4,105: | Line 4,105: | ||
map->Find("thirteen")->As(IntHolder)->GetValue()->PrintLine(); |
map->Find("thirteen")->As(IntHolder)->GetValue()->PrintLine(); |
||
map->Find("seven")->As(IntHolder)->GetValue()->PrintLine(); |
map->Find("seven")->As(IntHolder)->GetValue()->PrintLine(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Hash table=== |
===Hash table=== |
||
< |
<syntaxhighlight lang=objeck> |
||
# create map |
# create map |
||
map := StringHash->New(); |
map := StringHash->New(); |
||
Line 4,119: | Line 4,119: | ||
map->Find("thirteen")->As(IntHolder)->GetValue()->PrintLine(); |
map->Find("thirteen")->As(IntHolder)->GetValue()->PrintLine(); |
||
map->Find("seven")->As(IntHolder)->GetValue()->PrintLine(); |
map->Find("seven")->As(IntHolder)->GetValue()->PrintLine(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
Line 4,125: | Line 4,125: | ||
You can use a NSDictionary to create an immutable hash. A dictionary can contain only objects; if you want store non objects like integer, you have to box it in NSNumber. |
You can use a NSDictionary to create an immutable hash. A dictionary can contain only objects; if you want store non objects like integer, you have to box it in NSNumber. |
||
< |
<syntaxhighlight lang=objc>NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: |
||
@"Joe Doe", @"name", |
@"Joe Doe", @"name", |
||
[NSNumber numberWithUnsignedInt:42], @"age", |
[NSNumber numberWithUnsignedInt:42], @"age", |
||
[NSNull null], @"extra", |
[NSNull null], @"extra", |
||
nil];</ |
nil];</syntaxhighlight> |
||
The same as the above with the new literal syntax in clang 3.1+ / Apple LLVM Compiler 4.0+ (XCode 4.4+) : |
The same as the above with the new literal syntax in clang 3.1+ / Apple LLVM Compiler 4.0+ (XCode 4.4+) : |
||
< |
<syntaxhighlight lang=objc>NSDictionary *dict = @{ |
||
@"name": @"Joe Doe", |
@"name": @"Joe Doe", |
||
@"age": @42, |
@"age": @42, |
||
@"extra": [NSNull null], |
@"extra": [NSNull null], |
||
};</ |
};</syntaxhighlight> |
||
To create a mutable dictionary, use NSMutableDictionary: |
To create a mutable dictionary, use NSMutableDictionary: |
||
< |
<syntaxhighlight lang=objc>NSMutableDictionary *dict = [NSMutableDictionary dictionary]; |
||
[dict setObject:@"Joe Doe" forKey:@"name"]; |
[dict setObject:@"Joe Doe" forKey:@"name"]; |
||
[dict setObject:[NSNumber numberWithInt:42] forKey:@"age"];</ |
[dict setObject:[NSNumber numberWithInt:42] forKey:@"age"];</syntaxhighlight> |
||
You can access value with objectForKey:. If a key does not exists, nil is returned. |
You can access value with objectForKey:. If a key does not exists, nil is returned. |
||
< |
<syntaxhighlight lang=objc>NSString *name = [dict objectForKey:@"name"]; |
||
unsigned age = [dict objectForKey:@"age"] unsignedIntValue]; |
unsigned age = [dict objectForKey:@"age"] unsignedIntValue]; |
||
id missing = [dict objectForKey:@"missing"];</ |
id missing = [dict objectForKey:@"missing"];</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
===Hash table=== |
===Hash table=== |
||
A simple idiom to create a hash table mapping strings to integers: |
A simple idiom to create a hash table mapping strings to integers: |
||
< |
<syntaxhighlight lang=ocaml>let hash = Hashtbl.create 0;; |
||
List.iter (fun (key, value) -> Hashtbl.add hash key value) |
List.iter (fun (key, value) -> Hashtbl.add hash key value) |
||
["foo", 5; "bar", 10; "baz", 15];;</ |
["foo", 5; "bar", 10; "baz", 15];;</syntaxhighlight> |
||
To retrieve a value: |
To retrieve a value: |
||
< |
<syntaxhighlight lang=ocaml>let bar = Hashtbl.find hash "bar";; (* bar = 10 *)</syntaxhighlight> |
||
To retrieve a value, returning a default if the key is not found: |
To retrieve a value, returning a default if the key is not found: |
||
< |
<syntaxhighlight lang=ocaml>let quux = try Hashtbl.find hash "quux" with Not_found -> some_value;;</syntaxhighlight> |
||
===Binary tree=== |
===Binary tree=== |
||
A simple idiom to create a persistent binary tree mapping strings to integers: |
A simple idiom to create a persistent binary tree mapping strings to integers: |
||
< |
<syntaxhighlight lang=ocaml>module String = struct |
||
type t = string |
type t = string |
||
let compare = Pervasives.compare |
let compare = Pervasives.compare |
||
Line 4,172: | Line 4,172: | ||
StringMap.empty |
StringMap.empty |
||
["foo", 5; "bar", 10; "baz", 15] |
["foo", 5; "bar", 10; "baz", 15] |
||
;;</ |
;;</syntaxhighlight> |
||
To retrieve a value: |
To retrieve a value: |
||
< |
<syntaxhighlight lang=ocaml>let bar = StringMap.find "bar" map;; (* bar = 10 *)</syntaxhighlight> |
||
To retrieve a value, returning a default if the key is not found: |
To retrieve a value, returning a default if the key is not found: |
||
< |
<syntaxhighlight lang=ocaml>let quux = try StringMap.find "quux" map with Not_found -> some_value;;</syntaxhighlight> |
||
===Association list=== |
===Association list=== |
||
Some list functions allow you to use a list as an associative map, although the access time is O(N) so a Hashtbl or binary tree should be used for larger data-sets. |
Some list functions allow you to use a list as an associative map, although the access time is O(N) so a Hashtbl or binary tree should be used for larger data-sets. |
||
< |
<syntaxhighlight lang=Ocaml>let dict = ["foo", 5; "bar", 10; "baz", 15] |
||
(* retrieve value *) |
(* retrieve value *) |
||
Line 4,185: | Line 4,185: | ||
(* see if key exists *) |
(* see if key exists *) |
||
print_endline (if List.mem_assoc "foo" dict then "key found" else "key missing")</ |
print_endline (if List.mem_assoc "foo" dict then "key found" else "key missing")</syntaxhighlight> |
||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
Line 4,192: | Line 4,192: | ||
You can use only values as keys (atomic numbers, constants) and, as exception, symbols (symbols are references, but unique). No strings, lists, vectors and other objects can be used directly. In such cases use hashes or similar mechanisms. |
You can use only values as keys (atomic numbers, constants) and, as exception, symbols (symbols are references, but unique). No strings, lists, vectors and other objects can be used directly. In such cases use hashes or similar mechanisms. |
||
< |
<syntaxhighlight lang=scheme> |
||
;;; empty associative array |
;;; empty associative array |
||
#empty |
#empty |
||
Line 4,224: | Line 4,224: | ||
(print my-new-map) |
(print my-new-map) |
||
; ==> #((1 . 100) (2 . 200) (7 . 777) (the-key . the-value)) |
; ==> #((1 . 100) (2 . 200) (7 . 777) (the-key . the-value)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|ooRexx}}== |
=={{header|ooRexx}}== |
||
Line 4,237: | Line 4,237: | ||
Defining the map: |
Defining the map: |
||
< |
<syntaxhighlight lang=ooRexx>map = .directory~new |
||
map["foo"] = 5 |
map["foo"] = 5 |
||
map["bar"] = 10 |
map["bar"] = 10 |
||
map["baz"] = 15 |
map["baz"] = 15 |
||
map["foo"] = 6 |
map["foo"] = 6 |
||
</syntaxhighlight> |
|||
</lang> |
|||
"Putting" a value for a key that already exists ("map["foo"] = 6" in this example) will replace and return the old value for the key. |
"Putting" a value for a key that already exists ("map["foo"] = 6" in this example) will replace and return the old value for the key. |
||
Retrieving a value: |
Retrieving a value: |
||
< |
<syntaxhighlight lang=ooRexx>item = map["foo"] -- => 6 |
||
item = map["invalid"] -- => .nil</ |
item = map["invalid"] -- => .nil</syntaxhighlight> |
||
Note that it is possible to put <code>.nil</code> as a value, so <code>.nil</code> being returned as a value is not sufficient for determining that the key is not in the collection. There is a <code>hasIndex</code> method for that. |
Note that it is possible to put <code>.nil</code> as a value, so <code>.nil</code> being returned as a value is not sufficient for determining that the key is not in the collection. There is a <code>hasIndex</code> method for that. |
||
Iterate over keys: |
Iterate over keys: |
||
< |
<syntaxhighlight lang=ooRexx>loop key over map |
||
say key |
say key |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Iterate over values: |
Iterate over values: |
||
< |
<syntaxhighlight lang=ooRexx>loop value over map~allItems |
||
say value |
say value |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Iterate over key, value pairs: |
Iterate over key, value pairs: |
||
< |
<syntaxhighlight lang=ooRexx> |
||
s = map~supplier |
s = map~supplier |
||
loop while s~available |
loop while s~available |
||
Line 4,267: | Line 4,267: | ||
s~next |
s~next |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OxygenBasic}}== |
=={{header|OxygenBasic}}== |
||
Not very efficient but the 'find' method could be optimised very easily. |
Not very efficient but the 'find' method could be optimised very easily. |
||
< |
<syntaxhighlight lang=oxygenbasic> |
||
def n 200 |
def n 200 |
||
Line 4,324: | Line 4,324: | ||
A.dat("computers")="LC99" ' |
A.dat("computers")="LC99" ' |
||
print A.dat("computers") 'result LC99 |
print A.dat("computers") 'result LC99 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
A mutable map is called a 'dictionary' in Oz: |
A mutable map is called a 'dictionary' in Oz: |
||
< |
<syntaxhighlight lang=oz>declare |
||
Dict = {Dictionary.new} |
Dict = {Dictionary.new} |
||
in |
in |
||
Line 4,336: | Line 4,336: | ||
Dict.foo := 20 |
Dict.foo := 20 |
||
{Inspect Dict}</ |
{Inspect Dict}</syntaxhighlight> |
||
'Records' can be consideres immutable maps: |
'Records' can be consideres immutable maps: |
||
< |
<syntaxhighlight lang=oz>declare |
||
Rec = name(foo:5 bar:10 baz:20) |
Rec = name(foo:5 bar:10 baz:20) |
||
in |
in |
||
{Inspect Rec}</ |
{Inspect Rec}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Line 4,348: | Line 4,348: | ||
GP's associative arrays are called maps, and can be created like so: |
GP's associative arrays are called maps, and can be created like so: |
||
< |
<syntaxhighlight lang=parigp>M = Map();</syntaxhighlight> |
||
They can be used as follows: |
They can be used as follows: |
||
< |
<syntaxhighlight lang=parigp>mapput(M, "key", "value"); |
||
mapput(M, 17, "different value"); |
mapput(M, 17, "different value"); |
||
mapput(M, "key2", Pi); |
mapput(M, "key2", Pi); |
||
mapget(M, "key2") \\ returns Pi |
mapget(M, "key2") \\ returns Pi |
||
mapisdefined(M, "key3") \\ returns 0 |
mapisdefined(M, "key3") \\ returns 0 |
||
mapdelete(M, "key2");</ |
mapdelete(M, "key2");</syntaxhighlight> |
||
In PARI the commands are <code>gtomap</code>, <code>mapput</code>, <code>mapget</code>, <code>mapisdefined</code>, and <code>mapdelete</code>. You can also use the solutions in [[Associative arrays/Creation/C]]. |
In PARI the commands are <code>gtomap</code>, <code>mapput</code>, <code>mapget</code>, <code>mapisdefined</code>, and <code>mapdelete</code>. You can also use the solutions in [[Associative arrays/Creation/C]]. |
||
Line 4,362: | Line 4,362: | ||
===Hash=== |
===Hash=== |
||
Definition: |
Definition: |
||
< |
<syntaxhighlight lang=perl># using => key does not need to be quoted unless it contains special chars |
||
my %hash = ( |
my %hash = ( |
||
key1 => 'val1', |
key1 => 'val1', |
||
Line 4,376: | Line 4,376: | ||
'three', -238.83, |
'three', -238.83, |
||
4, 'val3', |
4, 'val3', |
||
);</ |
);</syntaxhighlight> |
||
Use: |
Use: |
||
< |
<syntaxhighlight lang=perl>print $hash{key1}; |
||
$hash{key1} = 'val1'; |
$hash{key1} = 'val1'; |
||
@hash{'key1', 'three'} = ('val1', -238.83);</ |
@hash{'key1', 'three'} = ('val1', -238.83);</syntaxhighlight> |
||
===HashRef=== |
===HashRef=== |
||
Definition: |
Definition: |
||
< |
<syntaxhighlight lang=perl>my $hashref = { |
||
key1 => 'val1', |
key1 => 'val1', |
||
'key-2' => 2, |
'key-2' => 2, |
||
three => -238.83, |
three => -238.83, |
||
4 => 'val3', |
4 => 'val3', |
||
}</ |
}</syntaxhighlight> |
||
Use: |
Use: |
||
< |
<syntaxhighlight lang=perl>print $hashref->{key1}; |
||
$hashref->{key1} = 'val1'; |
$hashref->{key1} = 'val1'; |
||
@{$hashref}{('key1', 'three')} = ('val1', -238.83);</ |
@{$hashref}{('key1', 'three')} = ('val1', -238.83);</syntaxhighlight> |
||
===Key Types=== |
===Key Types=== |
||
Line 4,416: | Line 4,416: | ||
integer tid=new_dict(), and pass that as an additional (final) parameter to the other routines (taking care not to miss |
integer tid=new_dict(), and pass that as an additional (final) parameter to the other routines (taking care not to miss |
||
any). When you have no further use for it, an entire dictionary can be removed by invoking destroy_dict(tid). |
any). When you have no further use for it, an entire dictionary can be removed by invoking destroy_dict(tid). |
||
<!--< |
<!--<syntaxhighlight lang=Phix>(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"one"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> |
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"one"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> |
||
Line 4,426: | Line 4,426: | ||
<span style="color: #7060A8;">deld</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> |
<span style="color: #7060A8;">deld</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">getd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- shows 0</span> |
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">getd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- shows 0</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang=Phixmonti>include ..\Utilitys.pmt |
||
def getd /# dict key -- dict data #/ |
def getd /# dict key -- dict data #/ |
||
Line 4,463: | Line 4,463: | ||
PI getd tostr print nl |
PI getd tostr print nl |
||
3 getd print |
3 getd print |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang=php>$array = array(); |
||
$array = []; // Simpler form of array initialization |
$array = []; // Simpler form of array initialization |
||
$array['foo'] = 'bar'; |
$array['foo'] = 'bar'; |
||
Line 4,486: | Line 4,486: | ||
// Check if key exists in the associative array |
// Check if key exists in the associative array |
||
echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null |
echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null |
||
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null</ |
echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null</syntaxhighlight> |
||
===Iterate over key/value=== |
===Iterate over key/value=== |
||
< |
<syntaxhighlight lang=php>foreach($array as $key => $value) |
||
{ |
{ |
||
echo "Key: $key Value: $value"; |
echo "Key: $key Value: $value"; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
Associative arrays are called "map" in Picat. |
Associative arrays are called "map" in Picat. |
||
< |
<syntaxhighlight lang=Picat>go => |
||
% Create an empty map |
% Create an empty map |
||
Line 4,532: | Line 4,532: | ||
nl. |
nl. |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 4,551: | Line 4,551: | ||
[http://software-lab.de/doc/refA.html#assoc association lists]. |
[http://software-lab.de/doc/refA.html#assoc association lists]. |
||
< |
<syntaxhighlight lang=PicoLisp>(put 'A 'foo 5) |
||
(put 'A 'bar 10) |
(put 'A 'bar 10) |
||
(put 'A 'baz 15) |
(put 'A 'baz 15) |
||
Line 4,566: | Line 4,566: | ||
foo 20 |
foo 20 |
||
bar 10 |
bar 10 |
||
baz 15</ |
baz 15</syntaxhighlight> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
Line 4,580: | Line 4,580: | ||
''indices()'' and ''values()'' can be used to enumerate the contents |
''indices()'' and ''values()'' can be used to enumerate the contents |
||
of an existing mapping. |
of an existing mapping. |
||
< |
<syntaxhighlight lang=Pike> |
||
mapping m = ([ "apple": "fruit", 17: "seventeen" ]); |
mapping m = ([ "apple": "fruit", 17: "seventeen" ]); |
||
write("indices: %O\nvalues: %O\n17: %O\n", |
write("indices: %O\nvalues: %O\n17: %O\n", |
||
Line 4,586: | Line 4,586: | ||
values(m), |
values(m), |
||
m[17]); |
m[17]); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 4,602: | Line 4,602: | ||
Since any data type can be used nested structures of arbitrary size can |
Since any data type can be used nested structures of arbitrary size can |
||
be constructed. |
be constructed. |
||
< |
<syntaxhighlight lang=Pike> |
||
mapping m2 = ([ "car": ([ "ford":17, "volvo":42 ]) ]); |
mapping m2 = ([ "car": ([ "ford":17, "volvo":42 ]) ]); |
||
write("#ford: %O, #volvo: %O\n", |
write("#ford: %O, #volvo: %O\n", |
||
m2->car->ford, |
m2->car->ford, |
||
m2["car"]["volvo"]); |
m2["car"]["volvo"]); |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 4,614: | Line 4,614: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang=pli>*process source xref attributes or(!); |
||
assocarr: Proc Options(main); |
assocarr: Proc Options(main); |
||
Dcl 1 aa, |
Dcl 1 aa, |
||
Line 4,662: | Line 4,662: | ||
End; |
End; |
||
End;</ |
End;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>added >1< -> spam< |
<pre>added >1< -> spam< |
||
Line 4,682: | Line 4,682: | ||
The following example code is a "record definition", which has nothing to do with associative arrays:- |
The following example code is a "record definition", which has nothing to do with associative arrays:- |
||
< |
<syntaxhighlight lang=PL/SQL>DECLARE |
||
type ThisIsNotAnAssocArrayType is record ( |
type ThisIsNotAnAssocArrayType is record ( |
||
myShape VARCHAR2(20), |
myShape VARCHAR2(20), |
||
Line 4,695: | Line 4,695: | ||
dbms_output.put_line ('assocArray.mySize: ' || assocArray.mySize); |
dbms_output.put_line ('assocArray.mySize: ' || assocArray.mySize); |
||
END; |
END; |
||
/</ |
/</syntaxhighlight> |
||
=={{header|Pop11}}== |
=={{header|Pop11}}== |
||
< |
<syntaxhighlight lang=pop11>;;; Create expandable hash table of initial size 50 and with default |
||
;;; value 0 (default value is returned when the item is absent). |
;;; value 0 (default value is returned when the item is absent). |
||
vars ht = newmapping([], 50, 0, true); |
vars ht = newmapping([], 50, 0, true); |
||
Line 4,719: | Line 4,719: | ||
printf(value, '%p\t'); |
printf(value, '%p\t'); |
||
printf(key, '%p\n'); |
printf(key, '%p\n'); |
||
endprocedure);</ |
endprocedure);</syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
< |
<syntaxhighlight lang=postscript> |
||
<</a 100 /b 200 /c 300>> |
<</a 100 /b 200 /c 300>> |
||
dup /a get = |
dup /a get = |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Potion}}== |
=={{header|Potion}}== |
||
< |
<syntaxhighlight lang=potion>mydictionary = (red=0xff0000, green=0x00ff00, blue=0x0000ff) |
||
redblue = "purple" |
redblue = "purple" |
||
Line 4,735: | Line 4,735: | ||
255 == mydictionary("blue") |
255 == mydictionary("blue") |
||
65280 == mydictionary("green") |
65280 == mydictionary("green") |
||
16711935 == mydictionary("purple")</ |
16711935 == mydictionary("purple")</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
An empty hash table can be created with: |
An empty hash table can be created with: |
||
< |
<syntaxhighlight lang=powershell>$hashtable = @{}</syntaxhighlight> |
||
A hash table can be initialized with key/value pairs: |
A hash table can be initialized with key/value pairs: |
||
< |
<syntaxhighlight lang=powershell>$hashtable = @{ |
||
"key1" = "value 1" |
"key1" = "value 1" |
||
key2 = 5 # if the key name has no spaces, no quotes are needed. |
key2 = 5 # if the key name has no spaces, no quotes are needed. |
||
}</ |
}</syntaxhighlight> |
||
Individual values can be assigned or replaced by either using a property-style access method or indexing into the table with the given key: |
Individual values can be assigned or replaced by either using a property-style access method or indexing into the table with the given key: |
||
< |
<syntaxhighlight lang=powershell>$hashtable.foo = "bar" |
||
$hashtable['bar'] = 42 |
$hashtable['bar'] = 42 |
||
$hashtable."a b" = 3.14 # keys can contain spaces, property-style access needs quotation marks, then |
$hashtable."a b" = 3.14 # keys can contain spaces, property-style access needs quotation marks, then |
||
$hashtable[5] = 8 # keys don't need to be strings</ |
$hashtable[5] = 8 # keys don't need to be strings</syntaxhighlight> |
||
NB. PowerShell compares strings as case-insensitive, that means the hashtable keys 'a' and 'A' are considered the same key. This happens when @{} is turned into a hashtable, but can be overridden by an explicit long-form: |
NB. PowerShell compares strings as case-insensitive, that means the hashtable keys 'a' and 'A' are considered the same key. This happens when @{} is turned into a hashtable, but can be overridden by an explicit long-form: |
||
< |
<syntaxhighlight lang=powershell># Case insensitive keys, both end up as the same key: |
||
$h=@{} |
$h=@{} |
||
$h['a'] = 1 |
$h['a'] = 1 |
||
Line 4,770: | Line 4,770: | ||
---- ----- |
---- ----- |
||
A 2 |
A 2 |
||
a 1 </ |
a 1 </syntaxhighlight> |
||
Similarly, values can be retrieved using either syntax: |
Similarly, values can be retrieved using either syntax: |
||
< |
<syntaxhighlight lang=powershell>$hashtable.key1 # value 1 |
||
$hashtable['key2'] # 5</ |
$hashtable['key2'] # 5</syntaxhighlight> |
||
It is common to see a hashtable literal used to create an object, by casting it to a new type: |
It is common to see a hashtable literal used to create an object, by casting it to a new type: |
||
< |
<syntaxhighlight lang=powershell>$obj = [PSCustomObject]@{ |
||
"key1" = "value 1" |
"key1" = "value 1" |
||
key2 = 5 |
key2 = 5 |
||
}</ |
}</syntaxhighlight> |
||
This is a convenience syntax, has less code and runs faster than other ways to create objects. |
This is a convenience syntax, has less code and runs faster than other ways to create objects. |
||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
We use the facts table for this purpose. |
We use the facts table for this purpose. |
||
< |
<syntaxhighlight lang=prolog> |
||
mymap(key1,value1). |
mymap(key1,value1). |
||
mymap(key2,value2). |
mymap(key2,value2). |
||
Line 4,789: | Line 4,789: | ||
?- mymap(key1,V). |
?- mymap(key1,V). |
||
V = value1 |
V = value1 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
Hashes are a built-in type called Map in Purebasic. |
Hashes are a built-in type called Map in Purebasic. |
||
< |
<syntaxhighlight lang=purebasic>NewMap dict.s() |
||
dict("country") = "Germany" |
dict("country") = "Germany" |
||
Debug dict("country")</ |
Debug dict("country")</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
Hashes are a built-in type called dictionaries (or mappings) in Python. |
Hashes are a built-in type called dictionaries (or mappings) in Python. |
||
< |
<syntaxhighlight lang=python>hash = dict() # 'dict' is the dictionary type. |
||
hash = dict(red="FF0000", green="00FF00", blue="0000FF") |
hash = dict(red="FF0000", green="00FF00", blue="0000FF") |
||
hash = { 'key1':1, 'key2':2, } |
hash = { 'key1':1, 'key2':2, } |
||
value = hash[key]</ |
value = hash[key]</syntaxhighlight> |
||
Numerous methods exist for the mapping type https://docs.python.org/3/library/stdtypes.html#mapping-types-dict |
Numerous methods exist for the mapping type https://docs.python.org/3/library/stdtypes.html#mapping-types-dict |
||
< |
<syntaxhighlight lang=python># empty dictionary |
||
d = {} |
d = {} |
||
d['spam'] = 1 |
d['spam'] = 1 |
||
Line 4,827: | Line 4,827: | ||
# iterating over (key, value) pairs |
# iterating over (key, value) pairs |
||
for key, value in d.iteritems(): |
for key, value in d.iteritems(): |
||
print key, value</ |
print key, value</syntaxhighlight> |
||
Note: Python dictionary keys can be of any arbitrary "hashable" type. The following contains several distinct key value pairs: |
Note: Python dictionary keys can be of any arbitrary "hashable" type. The following contains several distinct key value pairs: |
||
< |
<syntaxhighlight lang=python>myDict = { '1': 'a string', 1: 'an integer', 1.0: 'a floating point number', (1,): 'a tuple' }</syntaxhighlight> |
||
(Some other languages such as ''awk'' and ''Perl'' evaluate all keys such that numerically or lexically equivalent expressions become identical entries in the hash or associative array). |
(Some other languages such as ''awk'' and ''Perl'' evaluate all keys such that numerically or lexically equivalent expressions become identical entries in the hash or associative array). |
||
Line 4,844: | Line 4,844: | ||
=== environment example === |
=== environment example === |
||
< |
<syntaxhighlight lang=r>> env <- new.env() |
||
> env[["x"]] <- 123 |
> env[["x"]] <- 123 |
||
> env[["x"]]</ |
> env[["x"]]</syntaxhighlight> |
||
<pre>[1] 123</pre> |
<pre>[1] 123</pre> |
||
< |
<syntaxhighlight lang=r>> index <- "1" |
||
> env[[index]] <- "rainfed hay" |
> env[[index]] <- "rainfed hay" |
||
> env[[index]]</ |
> env[[index]]</syntaxhighlight> |
||
<pre>[1] "rainfed hay"</pre> |
<pre>[1] "rainfed hay"</pre> |
||
<lang |
<syntaxhighlight lang=r>> env[["1"]]</syntaxhighlight> |
||
<pre>[1] "rainfed hay"</pre> |
<pre>[1] "rainfed hay"</pre> |
||
<lang |
<syntaxhighlight lang=r>> env</syntaxhighlight> |
||
<pre><environment: 0xb7cd560></pre> |
<pre><environment: 0xb7cd560></pre> |
||
<lang |
<syntaxhighlight lang=r>> print(env)</syntaxhighlight> |
||
<pre><environment: 0xb7cd560></pre> |
<pre><environment: 0xb7cd560></pre> |
||
=== vector example === |
=== vector example === |
||
< |
<syntaxhighlight lang=r>> x <- c(hello=1, world=2, "!"=3) |
||
> print(x)</ |
> print(x)</syntaxhighlight> |
||
<pre>hello world ! |
<pre>hello world ! |
||
1 2 3</pre> |
1 2 3</pre> |
||
<lang |
<syntaxhighlight lang=r>> print(names(x))</syntaxhighlight> |
||
<pre>[1] "hello" "world" "!"</pre> |
<pre>[1] "hello" "world" "!"</pre> |
||
<lang |
<syntaxhighlight lang=r>print(unname(x))</syntaxhighlight> |
||
<pre>[1] 1 2 3</pre> |
<pre>[1] 1 2 3</pre> |
||
=== list example === |
=== list example === |
||
< |
<syntaxhighlight lang=R>> a <- list(a=1, b=2, c=3.14, d="xyz") |
||
> print(a)</ |
> print(a)</syntaxhighlight> |
||
<pre>$a |
<pre>$a |
||
[1] 1 |
[1] 1 |
||
Line 4,885: | Line 4,885: | ||
$d |
$d |
||
[1] "xyz"</pre> |
[1] "xyz"</pre> |
||
<lang |
<syntaxhighlight lang=r>> print(names(a))</syntaxhighlight> |
||
<pre>[1] "a" "b" "c" "d"</pre> |
<pre>[1] "a" "b" "c" "d"</pre> |
||
<lang |
<syntaxhighlight lang=r>> print(unname(a))</syntaxhighlight> |
||
<pre>[[1]] |
<pre>[[1]] |
||
[1] 1 |
[1] 1 |
||
Line 4,903: | Line 4,903: | ||
In Racket, hash tables are natively supported and encouraged over association lists in many cases. Data structures that behave like dictionaries support a unified interface. |
In Racket, hash tables are natively supported and encouraged over association lists in many cases. Data structures that behave like dictionaries support a unified interface. |
||
< |
<syntaxhighlight lang=racket> |
||
#lang racket |
#lang racket |
||
Line 4,917: | Line 4,917: | ||
(dict-ref a-list 'a) ; => 5 |
(dict-ref a-list 'a) ; => 5 |
||
(dict-ref table 'a) ; => 5 |
(dict-ref table 'a) ; => 5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 4,925: | Line 4,925: | ||
The fatarrow, <code>=></code>, is no longer just a quoting comma; it now constructs a <code>Pair</code> object. But you can still define a hash with an ordinary list of even length. |
The fatarrow, <code>=></code>, is no longer just a quoting comma; it now constructs a <code>Pair</code> object. But you can still define a hash with an ordinary list of even length. |
||
< |
<syntaxhighlight lang=perl6>my %h1 = key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3'; |
||
my %h2 = 'key1', 'val1', 'key-2', 2, 'three', -238.83, 4, 'val3'; |
my %h2 = 'key1', 'val1', 'key-2', 2, 'three', -238.83, 4, 'val3'; |
||
Line 4,952: | Line 4,952: | ||
class C {}; |
class C {}; |
||
my %cash{C}; |
my %cash{C}; |
||
%cash{C.new} = 1;</ |
%cash{C.new} = 1;</syntaxhighlight> |
||
=={{header|Raven}}== |
=={{header|Raven}}== |
||
< |
<syntaxhighlight lang=raven>{ 'a' 1 'b' 2 'c' 3.14 'd' 'xyz' } as a_hash |
||
a_hash print |
a_hash print |
||
Line 4,967: | Line 4,967: | ||
6.28 a_hash 'c' set # set key 'c' |
6.28 a_hash 'c' set # set key 'c' |
||
a_hash.'c' # get key 'c' shorthand |
a_hash.'c' # get key 'c' shorthand |
||
6.28 a_hash:'c' # set key 'c' shorthand</ |
6.28 a_hash:'c' # set key 'c' shorthand</syntaxhighlight> |
||
Null is returned for unknown keys. |
Null is returned for unknown keys. |
||
Line 4,973: | Line 4,973: | ||
=={{header|Relation}}== |
=={{header|Relation}}== |
||
< |
<syntaxhighlight lang=relation> |
||
relation key, value |
relation key, value |
||
insert "foo", "bar" |
insert "foo", "bar" |
||
Line 4,982: | Line 4,982: | ||
select key == "fruit" |
select key == "fruit" |
||
print |
print |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''assert''' will show an error, if a key is used twice. However, it not stop the insertion. |
'''assert''' will show an error, if a key is used twice. However, it not stop the insertion. |
||
Line 5,005: | Line 5,005: | ||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
< |
<syntaxhighlight lang=Retro>with hashTable' |
||
hashTable constant table |
hashTable constant table |
||
Line 5,012: | Line 5,012: | ||
table @" first" putn |
table @" first" putn |
||
table @" second" puts</ |
table @" second" puts</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
===version 1=== |
===version 1=== |
||
Associative arrays are called ''stem variables'' in Rexx. |
Associative arrays are called ''stem variables'' in Rexx. |
||
< |
<syntaxhighlight lang=Rexx>/* Rexx */ |
||
key0 = '0' |
key0 = '0' |
||
Line 5,026: | Line 5,026: | ||
Say 'stem.key0= 'stem.key /* Display a value for a key that wasn't set */ |
Say 'stem.key0= 'stem.key /* Display a value for a key that wasn't set */ |
||
Say 'stem.key1= 'stem.key1 /* Display a value for a key that was set */</ |
Say 'stem.key1= 'stem.key1 /* Display a value for a key that was set */</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>stem.key0= . |
<pre>stem.key0= . |
||
Line 5,032: | Line 5,032: | ||
===version 2=== |
===version 2=== |
||
< |
<syntaxhighlight lang=rexx>/*REXX program shows how to set/display values for an associative array.*/ |
||
/*┌────────────────────────────────────────────────────────────────────┐ |
/*┌────────────────────────────────────────────────────────────────────┐ |
||
│ The (below) two REXX statements aren't really necessary, but it │ |
│ The (below) two REXX statements aren't really necessary, but it │ |
||
Line 5,058: | Line 5,058: | ||
yyy='RI' |
yyy='RI' |
||
say 'capital of' stateN.yyy "is" stateC.yyy |
say 'capital of' stateN.yyy "is" stateC.yyy |
||
/*stick a fork in it, we're done.*/</ |
/*stick a fork in it, we're done.*/</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,067: | Line 5,067: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang=ring> |
||
# Project Associative array/Creation |
# Project Associative array/Creation |
||
Line 5,075: | Line 5,075: | ||
see find(myarray,"two",1) + nl |
see find(myarray,"two",1) + nl |
||
see find(myarray,2,2) + nl |
see find(myarray,2,2) + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 5,084: | Line 5,084: | ||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
Associative arrays are called ''lists'' in RLaB. |
Associative arrays are called ''lists'' in RLaB. |
||
< |
<syntaxhighlight lang=RLaB> |
||
x = <<>>; // create an empty list using strings as identifiers. |
x = <<>>; // create an empty list using strings as identifiers. |
||
x.red = strtod("0xff0000"); // RLaB doesn't deal with hexadecimal numbers directly. Thus we |
x.red = strtod("0xff0000"); // RLaB doesn't deal with hexadecimal numbers directly. Thus we |
||
Line 5,110: | Line 5,110: | ||
{ x.[i] = i; } // assign to the element of list ''i'' the real value equal to i. |
{ x.[i] = i; } // assign to the element of list ''i'' the real value equal to i. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
A hash object that returns [[nil]] for unknown keys |
A hash object that returns [[nil]] for unknown keys |
||
< |
<syntaxhighlight lang=ruby>hash={} |
||
hash[666]='devil' |
hash[666]='devil' |
||
hash[777] # => nil |
hash[777] # => nil |
||
hash[666] # => 'devil'</ |
hash[666] # => 'devil'</syntaxhighlight> |
||
A hash object that returns 'unknown key' for unknown keys |
A hash object that returns 'unknown key' for unknown keys |
||
< |
<syntaxhighlight lang=ruby>hash=Hash.new('unknown key') |
||
hash[666]='devil' |
hash[666]='devil' |
||
hash[777] # => 'unknown key' |
hash[777] # => 'unknown key' |
||
hash[666] # => 'devil'</ |
hash[666] # => 'devil'</syntaxhighlight> |
||
A hash object that returns "unknown key #{key}" for unknown keys |
A hash object that returns "unknown key #{key}" for unknown keys |
||
< |
<syntaxhighlight lang=ruby>hash=Hash.new{|h,k| "unknown key #{k}"} |
||
hash[666]='devil' |
hash[666]='devil' |
||
hash[777] # => 'unknown key 777' |
hash[777] # => 'unknown key 777' |
||
hash[666] # => 'devil'</ |
hash[666] # => 'devil'</syntaxhighlight> |
||
A hash object that adds "key #{key} was added at #{Time.now}" to the hash the first time an unknown key is seen |
A hash object that adds "key #{key} was added at #{Time.now}" to the hash the first time an unknown key is seen |
||
< |
<syntaxhighlight lang=ruby>hash=Hash.new{|h,k|h[k]="key #{k} was added at #{Time.now}"} |
||
hash[777] # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011' |
hash[777] # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011' |
||
hash[555] # => 'key 555 was added at Sun Apr 03 13:50:01 -0700 2011' |
hash[555] # => 'key 555 was added at Sun Apr 03 13:50:01 -0700 2011' |
||
hash[777] # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011'</ |
hash[777] # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011'</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang=rust>use std::collections::HashMap; |
||
fn main() { |
fn main() { |
||
let mut olympic_medals = HashMap::new(); |
let mut olympic_medals = HashMap::new(); |
||
Line 5,146: | Line 5,146: | ||
olympic_medals.insert("Germany", (252, 260, 270)); |
olympic_medals.insert("Germany", (252, 260, 270)); |
||
println!("{:?}", olympic_medals); |
println!("{:?}", olympic_medals); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Sather}}== |
=={{header|Sather}}== |
||
< |
<syntaxhighlight lang=sather>class MAIN is |
||
main is |
main is |
||
-- creation of a map between strings and integers |
-- creation of a map between strings and integers |
||
Line 5,169: | Line 5,169: | ||
end; |
end; |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang=Scala>// immutable maps |
||
var map = Map(1 -> 2, 3 -> 4, 5 -> 6) |
var map = Map(1 -> 2, 3 -> 4, 5 -> 6) |
||
map(3) // 4 |
map(3) // 4 |
||
map = map + (44 -> 99) // maps are immutable, so we have to assign the result of adding elements |
map = map + (44 -> 99) // maps are immutable, so we have to assign the result of adding elements |
||
map.isDefinedAt(33) // false |
map.isDefinedAt(33) // false |
||
map.isDefinedAt(44) // true</ |
map.isDefinedAt(44) // true</syntaxhighlight> |
||
< |
<syntaxhighlight lang=scala>// mutable maps (HashSets) |
||
import scala.collection.mutable.HashMap |
import scala.collection.mutable.HashMap |
||
val hash = new HashMap[Int, Int] |
val hash = new HashMap[Int, Int] |
||
Line 5,188: | Line 5,188: | ||
hash.contains(33) // false |
hash.contains(33) // false |
||
hash.isDefinedAt(33) // same as contains |
hash.isDefinedAt(33) // same as contains |
||
hash.contains(44) // true</ |
hash.contains(44) // true</syntaxhighlight> |
||
< |
<syntaxhighlight lang=scala>// iterate over key/value |
||
hash.foreach {e => println("key "+e._1+" value "+e._2)} // e is a 2 element Tuple |
hash.foreach {e => println("key "+e._1+" value "+e._2)} // e is a 2 element Tuple |
||
// same with for syntax |
// same with for syntax |
||
for((k,v) <- hash) println("key " + k + " value " + v)</ |
for((k,v) <- hash) println("key " + k + " value " + v)</syntaxhighlight> |
||
< |
<syntaxhighlight lang=scala>// items in map where the key is greater than 3 |
||
map.filter {k => k._1 > 3} // Map(5 -> 6, 44 -> 99) |
map.filter {k => k._1 > 3} // Map(5 -> 6, 44 -> 99) |
||
// same with for syntax |
// same with for syntax |
||
for((k, v) <- map; if k > 3) yield (k,v)</ |
for((k, v) <- map; if k > 3) yield (k,v)</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
Scheme has association lists (alists), which are inefficient, ordered maps with arbitrary keys and values. |
Scheme has association lists (alists), which are inefficient, ordered maps with arbitrary keys and values. |
||
< |
<syntaxhighlight lang=scheme>(define my-dict '((a b) (1 hello) ("c" (a b c))) |
||
(assoc 'a my-dict) ; evaluates to '(a b)</ |
(assoc 'a my-dict) ; evaluates to '(a b)</syntaxhighlight> |
||
Hash tables are provided by SRFI-69 [http://srfi.schemers.org/srfi-69/srfi-69.html]. Many Scheme implementation also provide native hash tables. |
Hash tables are provided by SRFI-69 [http://srfi.schemers.org/srfi-69/srfi-69.html]. Many Scheme implementation also provide native hash tables. |
||
< |
<syntaxhighlight lang=scheme>(define my-alist '((a b) (1 hello) ("c" (a b c))) |
||
(define my-hash (alist->hash-table my-alist))</ |
(define my-hash (alist->hash-table my-alist))</syntaxhighlight> |
||
The R6RS standard specifies support for hashtables in the [http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-14.html#node_chap_13 standard libraries] document. |
The R6RS standard specifies support for hashtables in the [http://www.r6rs.org/final/html/r6rs-lib/r6rs-lib-Z-H-14.html#node_chap_13 standard libraries] document. |
||
< |
<syntaxhighlight lang=scheme>#!r6rs |
||
(import (rnrs base) |
(import (rnrs base) |
||
Line 5,222: | Line 5,222: | ||
(hashtable-set! my-hash 'a 'b) |
(hashtable-set! my-hash 'a 'b) |
||
(hashtable-set! my-hash 1 'hello) |
(hashtable-set! my-hash 1 'hello) |
||
(hashtable-set! my-hash "c" '(a b c))</ |
(hashtable-set! my-hash "c" '(a b c))</syntaxhighlight> |
||
=== A ''persistent'' associative array from scratch === |
=== A ''persistent'' associative array from scratch === |
||
Line 5,236: | Line 5,236: | ||
Associate arrays are not part of the Scheme language itself, but are compiler/interpreter or library add-ons. So I feel justified in presenting this sketch of yet another library add-on. |
Associate arrays are not part of the Scheme language itself, but are compiler/interpreter or library add-ons. So I feel justified in presenting this sketch of yet another library add-on. |
||
< |
<syntaxhighlight lang=scheme>(cond-expand |
||
(r7rs) |
(r7rs) |
||
(chicken (import r7rs))) |
(chicken (import r7rs))) |
||
Line 5,618: | Line 5,618: | ||
)) |
)) |
||
(else))</ |
(else))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,642: | Line 5,642: | ||
Seed7 uses the type [http://seed7.sourceforge.net/manual/types.htm#hash hash] to support associative arrays. |
Seed7 uses the type [http://seed7.sourceforge.net/manual/types.htm#hash hash] to support associative arrays. |
||
< |
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i"; |
||
# Define hash type |
# Define hash type |
||
Line 5,686: | Line 5,686: | ||
writeln("key: " <& stri <& ", value: " <& number); |
writeln("key: " <& stri <& ", value: " <& number); |
||
end for; |
end for; |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|SenseTalk}}== |
=={{header|SenseTalk}}== |
||
Associative arrays in SenseTalk are called property lists, or objects. |
Associative arrays in SenseTalk are called property lists, or objects. |
||
< |
<syntaxhighlight lang=sensetalk>put {} into emptyPlist |
||
put an empty property list into emptyPlist2 |
put an empty property list into emptyPlist2 |
||
Line 5,698: | Line 5,698: | ||
put "!!!" after the occupation of Einstein |
put "!!!" after the occupation of Einstein |
||
put Einstein |
put Einstein |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 5,706: | Line 5,706: | ||
=={{header|SETL}}== |
=={{header|SETL}}== |
||
Associative arrays (referred to in SETL terminology as <i>maps</i>) are implemented as sets whose only members are tuples of length 2. Create such a set: |
Associative arrays (referred to in SETL terminology as <i>maps</i>) are implemented as sets whose only members are tuples of length 2. Create such a set: |
||
< |
<syntaxhighlight lang=setl>m := {['foo', 'a'], ['bar', 'b'], ['baz', 'c']};</syntaxhighlight> |
||
We can then index the set, or map, with the first element of a constituent tuple to return that tuple's second element: |
We can then index the set, or map, with the first element of a constituent tuple to return that tuple's second element: |
||
< |
<syntaxhighlight lang=setl>print( m('bar') );</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>b</pre> |
<pre>b</pre> |
||
If the map might contain more than one value associated with the same key, we can return the set of them (in this instance a unit set because the keys are in fact unique): |
If the map might contain more than one value associated with the same key, we can return the set of them (in this instance a unit set because the keys are in fact unique): |
||
< |
<syntaxhighlight lang=setl>print( m{'bar'} );</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>{b}</pre> |
<pre>{b}</pre> |
||
=={{header|SETL4}}== |
=={{header|SETL4}}== |
||
< |
<syntaxhighlight lang=Setl4> |
||
* Iterate over key-value pairs of a map |
* Iterate over key-value pairs of a map |
||
Line 5,742: | Line 5,742: | ||
out('next domain entry',next(d)) :s(next) |
out('next domain entry',next(d)) :s(next) |
||
done |
done |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang=ruby>var hash = Hash.new( |
||
key1 => 'value1', |
key1 => 'value1', |
||
key2 => 'value2', |
key2 => 'value2', |
||
Line 5,751: | Line 5,751: | ||
# Add a new key-value pair |
# Add a new key-value pair |
||
hash{:key3} = 'value3';</ |
hash{:key3} = 'value3';</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang=slate>Dictionary new*, 'MI' -> 'Michigan', 'MN' -> 'Minnesota'</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
< |
<syntaxhighlight lang=smalltalk>states := Dictionary new. |
||
states at: 'MI' put: 'Michigan'. |
states at: 'MI' put: 'Michigan'. |
||
states at: 'MN' put: 'Minnesota'.</ |
states at: 'MN' put: 'Minnesota'.</syntaxhighlight> |
||
alternative: |
alternative: |
||
< |
<syntaxhighlight lang=smalltalk>Dictionary withAssociations:{ 'MI' -> 'Michigan' . 'MN' -> 'Minnesota'}</syntaxhighlight> |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
< |
<syntaxhighlight lang=snobol4> t = table() |
||
t<"red"> = "#ff0000" |
t<"red"> = "#ff0000" |
||
t<"green"> = "#00ff00" |
t<"green"> = "#00ff00" |
||
Line 5,773: | Line 5,773: | ||
output = t<"blue"> |
output = t<"blue"> |
||
output = t<"green"> |
output = t<"green"> |
||
end</ |
end</syntaxhighlight> |
||
=={{header|SQL}}== |
=={{header|SQL}}== |
||
< |
<syntaxhighlight lang=SQL> |
||
REM Create a table to associate keys with values |
REM Create a table to associate keys with values |
||
CREATE TABLE associative_array ( KEY_COLUMN VARCHAR2(10), VALUE_COLUMN VARCHAR2(100)); . |
CREATE TABLE associative_array ( KEY_COLUMN VARCHAR2(10), VALUE_COLUMN VARCHAR2(100)); . |
||
Line 5,783: | Line 5,783: | ||
REM Retrieve a key value pair |
REM Retrieve a key value pair |
||
SELECT aa.value_column FROM associative_array aa where aa.key_column = 'KEY'; |
SELECT aa.value_column FROM associative_array aa where aa.key_column = 'KEY'; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|SQL PL}}== |
=={{header|SQL PL}}== |
||
{{works with|Db2 LUW}} version 9.7 or higher. |
{{works with|Db2 LUW}} version 9.7 or higher. |
||
With SQL PL: |
With SQL PL: |
||
< |
<syntaxhighlight lang=sql pl> |
||
--#SET TERMINATOR @ |
--#SET TERMINATOR @ |
||
Line 5,807: | Line 5,807: | ||
CALL DBMS_OUTPUT.PUT_LINE(HASH['5']); |
CALL DBMS_OUTPUT.PUT_LINE(HASH['5']); |
||
END@ |
END@ |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 5,827: | Line 5,827: | ||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<syntaxhighlight lang=stata>mata |
||
a=asarray_create() |
a=asarray_create() |
||
Line 5,844: | Line 5,844: | ||
// End Mata session |
// End Mata session |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang=swift>// make an empty map |
||
var a = [String: Int]() |
var a = [String: Int]() |
||
// or |
// or |
||
Line 5,859: | Line 5,859: | ||
// make a map with a literal |
// make a map with a literal |
||
var d = ["foo": 2, "bar": 42, "baz": -1]</ |
var d = ["foo": 2, "bar": 42, "baz": -1]</syntaxhighlight> |
||
=={{header|Symsyn}}== |
=={{header|Symsyn}}== |
||
Symsyn implements Hash as a list of strings. Each name/value or key/value pair is stored in another string. The name/value pair is in the format 'name=value', the '=' is reserved. |
Symsyn implements Hash as a list of strings. Each name/value or key/value pair is stored in another string. The name/value pair is in the format 'name=value', the '=' is reserved. |
||
< |
<syntaxhighlight lang=Symsyn> |
||
#+ 'name=bob' $hash | add to hash |
#+ 'name=bob' $hash | add to hash |
||
#? 'name' $hash $S | find 'name' and return 'bob' in $S |
#? 'name' $hash $S | find 'name' and return 'bob' in $S |
||
#- 'name' $hash | delete 'name=bob' from hash |
#- 'name' $hash | delete 'name=bob' from hash |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
All arrays in Tcl are associative. |
All arrays in Tcl are associative. |
||
< |
<syntaxhighlight lang=tcl># Create one element at a time: |
||
set hash(foo) 5 |
set hash(foo) 5 |
||
Line 5,887: | Line 5,887: | ||
foreach key [array names hash] { |
foreach key [array names hash] { |
||
puts $hash($key) |
puts $hash($key) |
||
}</ |
}</syntaxhighlight> |
||
Tcl also provides associative map values (called “dictionaries”) from 8.5 onwards. |
Tcl also provides associative map values (called “dictionaries”) from 8.5 onwards. |
||
<br> |
<br> |
||
{{works with|Tcl|8.5}} |
{{works with|Tcl|8.5}} |
||
< |
<syntaxhighlight lang=tcl># Create in bulk |
||
set d [dict create foo 5 bar 10 baz 15] |
set d [dict create foo 5 bar 10 baz 15] |
||
Line 5,911: | Line 5,911: | ||
# Output the whole dictionary (since it is a Tcl value itself) |
# Output the whole dictionary (since it is a Tcl value itself) |
||
puts $d</ |
puts $d</syntaxhighlight> |
||
=={{header|Toka}}== |
=={{header|Toka}}== |
||
Toka provides associative arrays via a library. |
Toka provides associative arrays via a library. |
||
< |
<syntaxhighlight lang=toka>needs asarray |
||
( create an associative array ) |
( create an associative array ) |
||
Line 5,929: | Line 5,929: | ||
( obtain and print the values ) |
( obtain and print the values ) |
||
" first" foo asarray.get . |
" first" foo asarray.get . |
||
" second" foo asarray.get .</ |
" second" foo asarray.get .</syntaxhighlight> |
||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|ksh}} |
{{works with|ksh}} |
||
< |
<syntaxhighlight lang=bash>typeset -A hash |
||
hash=( [key1]=val1 [key2]=val2 ) |
hash=( [key1]=val1 [key2]=val2 ) |
||
hash[key3]=val3 |
hash[key3]=val3 |
||
echo "${hash[key3]}"</ |
echo "${hash[key3]}"</syntaxhighlight> |
||
{{works with|bash}} |
{{works with|bash}} |
||
assigning values is the same as ksh, but to declare the variable as an associative array: |
assigning values is the same as ksh, but to declare the variable as an associative array: |
||
<lang |
<syntaxhighlight lang=bash>declare -A hash</syntaxhighlight> |
||
=={{header|UnixPipes}}== |
=={{header|UnixPipes}}== |
||
A key value file can be considered as an associative array |
A key value file can be considered as an associative array |
||
< |
<syntaxhighlight lang=bash>map='p.map' |
||
function init() { |
function init() { |
||
Line 5,987: | Line 5,987: | ||
put c cow |
put c cow |
||
get c |
get c |
||
dump</ |
dump</syntaxhighlight> |
||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
{{libheader|Gee}} |
{{libheader|Gee}} |
||
< |
<syntaxhighlight lang=vala> |
||
using Gee; |
using Gee; |
||
Line 6,009: | Line 6,009: | ||
stdout.printf("%d\n", map.get("two")); |
stdout.printf("%d\n", map.get("two")); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
Compile with flag: <pre> --pkg gee-1.0 </pre> |
Compile with flag: <pre> --pkg gee-1.0 </pre> |
||
Line 6,016: | Line 6,016: | ||
See '''[https://msdn.microsoft.com/en-us/library/x4k5wbx4.aspx here]''' in the MSDN the reference for the Dictionary object that can be used in VBA. The following example shows how to create a dictionary, add/remove keys, change a key or a value, and check the existence of a key. |
See '''[https://msdn.microsoft.com/en-us/library/x4k5wbx4.aspx here]''' in the MSDN the reference for the Dictionary object that can be used in VBA. The following example shows how to create a dictionary, add/remove keys, change a key or a value, and check the existence of a key. |
||
< |
<syntaxhighlight lang=vb>Option Explicit |
||
Sub Test() |
Sub Test() |
||
Dim h As Object |
Dim h As Object |
||
Line 6,031: | Line 6,031: | ||
h.RemoveAll |
h.RemoveAll |
||
Debug.Print h.Count |
Debug.Print h.Count |
||
End Sub</ |
End Sub</syntaxhighlight> |
||
=={{header|Vim Script}}== |
=={{header|Vim Script}}== |
||
Dictionary keys are always strings. |
Dictionary keys are always strings. |
||
< |
<syntaxhighlight lang=vim>" Creating a dictionary with some initial values |
||
let dict = {"one": 1, "two": 2} |
let dict = {"one": 1, "two": 2} |
||
Line 6,054: | Line 6,054: | ||
let one = remove(dict, "one") |
let one = remove(dict, "one") |
||
unlet dict["two"] |
unlet dict["two"] |
||
unlet dict.three</ |
unlet dict.three</syntaxhighlight> |
||
=={{header|Visual FoxPro}}== |
=={{header|Visual FoxPro}}== |
||
Visual FoxPro has a collection class which can be used for this. |
Visual FoxPro has a collection class which can be used for this. |
||
< |
<syntaxhighlight lang=vfp> |
||
LOCAL loCol As Collection, k, n, o |
LOCAL loCol As Collection, k, n, o |
||
CLEAR |
CLEAR |
||
Line 6,098: | Line 6,098: | ||
ENDPROC |
ENDPROC |
||
ENDDEFINE |
ENDDEFINE |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Vlang}}== |
=={{header|Vlang}}== |
||
< |
<syntaxhighlight lang=vlang>fn main() { |
||
// make empty map |
// make empty map |
||
mut my_map := map[string]int{} |
mut my_map := map[string]int{} |
||
Line 6,120: | Line 6,120: | ||
'baz': -1 |
'baz': -1 |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
< |
<syntaxhighlight lang=wart>h <- (table 'a 1 'b 2) |
||
h 'a |
h 'a |
||
=> 1</ |
=> 1</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
Wren has a Map class built in. |
Wren has a Map class built in. |
||
< |
<syntaxhighlight lang=ecmascript>var fruit = {} // creates an empty map |
||
fruit[1] = "orange" // associates a key of 1 with "orange" |
fruit[1] = "orange" // associates a key of 1 with "orange" |
||
fruit[2] = "apple" // associates a key of 2 with "apple" |
fruit[2] = "apple" // associates a key of 2 with "apple" |
||
Line 6,146: | Line 6,146: | ||
System.print(capitals) // prints all remaining entries |
System.print(capitals) // prints all remaining entries |
||
System.print(capitals.count) // prints the number of remaining entries |
System.print(capitals.count) // prints the number of remaining entries |
||
System.print(capitals["Sweden"]) // prints the entry for Sweden (null as there isn't one)</ |
System.print(capitals["Sweden"]) // prints the entry for Sweden (null as there isn't one)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 6,162: | Line 6,162: | ||
=={{header|XLISP}}== |
=={{header|XLISP}}== |
||
XLISP refers to associative arrays as tables. The <tt>MAKE-TABLE</tt> function returns a new empty table, for instance: |
XLISP refers to associative arrays as tables. The <tt>MAKE-TABLE</tt> function returns a new empty table, for instance: |
||
< |
<syntaxhighlight lang=lisp>(define starlings (make-table))</syntaxhighlight> |
||
Values can then be inserted using <tt>TABLE-SET!</tt>: |
Values can then be inserted using <tt>TABLE-SET!</tt>: |
||
< |
<syntaxhighlight lang=lisp>(table-set! starlings "Common starling" "Sturnus vulgaris") |
||
(table-set! starlings "Abbot's starling" "Poeoptera femoralis") |
(table-set! starlings "Abbot's starling" "Poeoptera femoralis") |
||
(table-set! starlings "Cape starling" "Lamprotornis nitens")</ |
(table-set! starlings "Cape starling" "Lamprotornis nitens")</syntaxhighlight> |
||
and retrieved using <tt>TABLE-REF</tt> with their keys: |
and retrieved using <tt>TABLE-REF</tt> with their keys: |
||
< |
<syntaxhighlight lang=lisp>(table-ref starlings "Cape starling")</syntaxhighlight> |
||
Output in a REPL: |
Output in a REPL: |
||
<pre>"Lamprotornis nitens"</pre> |
<pre>"Lamprotornis nitens"</pre> |
||
Other functions provided for tables include <tt>MAP-OVER-TABLE-ENTRIES</tt>, which takes a table and a function of two arguments and applies the function to each entry (using the key and value as the two arguments), for instance: |
Other functions provided for tables include <tt>MAP-OVER-TABLE-ENTRIES</tt>, which takes a table and a function of two arguments and applies the function to each entry (using the key and value as the two arguments), for instance: |
||
< |
<syntaxhighlight lang=lisp>(map-over-table-entries starlings (lambda (x y) (print (string-append x " (Linnaean name " y ")"))))</syntaxhighlight> |
||
Output in a REPL: |
Output in a REPL: |
||
<pre>"Abbott's starling (Linnaean name Poeoptera femoralis)" |
<pre>"Abbott's starling (Linnaean name Poeoptera femoralis)" |
||
Line 6,179: | Line 6,179: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang=XPL0>include c:\cxpl\stdlib; |
||
char Dict(10,10); |
char Dict(10,10); |
||
int Entries; |
int Entries; |
||
Line 6,205: | Line 6,205: | ||
ChOut(0, Lookup("beta")); CrLf(0); |
ChOut(0, Lookup("beta")); CrLf(0); |
||
ChOut(0, Lookup("omega")); CrLf(0); |
ChOut(0, Lookup("omega")); CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
For greater speed a hashing algorithm should be used to look up items in |
For greater speed a hashing algorithm should be used to look up items in |
||
Line 6,218: | Line 6,218: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang=zkl>zkl: Dictionary("one",1, "two",2, "three",3) |
||
D(two:2,three:3,one:1) |
D(two:2,three:3,one:1) |
||
zkl: T("one",1, "two",2, "three",3).toDictionary() |
zkl: T("one",1, "two",2, "three",3).toDictionary() |
||
D(two:2,three:3,one:1)</ |
D(two:2,three:3,one:1)</syntaxhighlight> |
||
{{omit from|Applesoft BASIC}} |
{{omit from|Applesoft BASIC}} |