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


*process source xref attributes or(!);
 assocarr: Proc Options(main);
 Dcl 1 aa,
      2 an Bin Fixed(31) Init(0),
      2 pairs(100),
       3 key Char(10) Var,
       3 val Char(10) Var;
 Dcl hi Char(10) Value((high(10)));
 Dcl i  Bin Fixed(31);
 Dcl k Char(10) Var;
 
 Call aadd('1','spam');
 Call aadd('2','eggs');
 Call aadd('3','foo');
 Call aadd('2','spam');
 Call aadd('4','spam');
 
 Put Skip(' ');
 Put Edit('Iterate over keys')(Skip,a);
 Do i=1 To an;
   k=key(i);
   Put Edit('>'!!k!!'< => >'!!aacc(k)!!'<')(Skip,a);
   End;
 
 aadd: Proc(k,v);
 Dcl (k,v) Char(*) Var;
 If aacc(k)^=hi Then
   Put Edit('Key >',k,'< would be a duplicate, not added.')
           (Skip,a,a,a);
 Else Do;
   an+=1;
   key(an)=k;
   val(an)=v;
   Put Edit('added >'!!k!!'< -> '!!v!!'<')(Skip,a);
   End;
 End;
 
 aacc: Proc(k) Returns(Char(10) Var);
 Dcl k Char(*) Var;
 Dcl v Char(10) Var;
 Dcl i Bin Fixed(31);
 Do i=1 To an;
   If key(i)=k Then
     Return(val(i));
   End;
 Return(hi);
 End;
 
 End;