Task

The goal is to create an associative array (also known as a dictionary, map, or hash).



Related tasks:

 Associative arrays/Iteration
 Hash from two arrays


See also

 Array
 Associative array: Creation, Iteration
 Collections
 Compound data type
 Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
 Linked list
 Queue: Definition, Usage
 Set
 Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
 Stack


$ include "seed7_05.s7i";
 
# Define hash type
const type: myHashType is hash [string] integer;
 
# Define hash table
var myHashType: aHash is myHashType.value;
 
const proc: main is func
  local
    var string: stri is "";
    var integer: number is 0;
  begin
    # Add elements
    aHash @:= ["foo"] 42;
    aHash @:= ["bar"] 100;
 
    # Check presence of an element
    if "foo" in aHash then
 
      # Access an element
      writeln(aHash["foo"]);
    end if;
 
    # Change an element
    aHash @:= ["foo"] 7;
 
    # Remove an element
    excl(aHash, "foo");
 
    # Loop over the hash values
    for number range aHash do
      writeln(number);
    end for;
 
    # Loop over the hash keys
    for key stri range aHash do
      writeln(stri);
    end for;
 
    # Loop over hash keys and values
    for number key stri range aHash do
      writeln("key: " <& stri <& ", value: " <& number);
    end for;
  end func;