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

Content deleted Content added
Standard ML: copy editing
Tcl: copy editing, switching order of "array" and "dict" subsections to be in accordance with introductory text
Line 1,804:
Another Standard ML implementation, [[Moscow ML]], also provides some associative containers. First, it provides polymorphic hash tables in the <code>Polyhash</code> structure. Also, some functional maps from the SML/NJ library above are available as <code>Binarymap</code>, <code>Splaymap</code>, and <code>Intmap</code> structures.
 
=== [[Tcl]] ===
There are two [[Tcl]] facilities that support associative -array semantics. An "array" is a collection of ''variables''. A '''"dict'''" is a full implementation of associative arrays.
 
====dict====
 
<syntaxhighlight lang=Tcl>
set phonebook [dict create {Sally Smart} 555-9999 {John Doe} 555-1212 {J. Random Hacker} 553-1337]
</syntaxhighlight>
 
To look up an item:
 
<syntaxhighlight lang=Tcl>
dict get $phonebook {John Doe}
</syntaxhighlight>
 
To iterate through a dict:
 
<syntaxhighlight lang=Tcl>
foreach {name number} $phonebook {
puts "name: $name\nnumber: $number"
</syntaxhighlight>
 
====array====
 
<syntaxhighlight lang=Tcl>
set {phonebook(Sally Smart)} 555-9999
Line 1,836 ⟶ 1,815:
</syntaxhighlight>
 
If there is a literal space character in the variable name, itthe name must be grouped using either curly brackets (no substitution performed) or double quotes (substitution is performed).
 
Alternatively, several array elements can be set inby a single command, by providingpresenting their mappings as a list (words containing whitespace are braced):
 
<syntaxhighlight lang=Tcl>
Line 1,844 ⟶ 1,823:
</syntaxhighlight>
 
To access one array entry and put it onto standard output:
 
<syntaxhighlight lang=Tcl>
Line 1,850 ⟶ 1,829:
</syntaxhighlight>
 
Which returns this result:
The result is here
 
<syntaxhighlight lang=Text>
Line 1,866 ⟶ 1,845:
<syntaxhighlight lang=Tcl>
{Sally Smart} 555-9999 {J. Random Hacker} 553-1337 {John Doe} 555-1212
</syntaxhighlight>
 
====dict====
<syntaxhighlight lang=Tcl>
set phonebook [dict create {Sally Smart} 555-9999 {John Doe} 555-1212 {J. Random Hacker} 553-1337]
</syntaxhighlight>
 
To look up an item:
 
<syntaxhighlight lang=Tcl>
dict get $phonebook {John Doe}
</syntaxhighlight>
 
To iterate through a dict:
 
<syntaxhighlight lang=Tcl>
foreach {name number} $phonebook {
puts "name: $name\nnumber: $number"
</syntaxhighlight>