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


 
def n 200
 
Class AssociativeArray
'=====================
 
  indexbase 1
  string s[n]
  sys    max
 
  method find(string k) as sys
  sys i,e
  e=max*2
  for i=1 to e step 2
    if k=s[i] then return i
  next
  end method
 
  method dat(string k) as string
  sys i=find(k)
  if i then return s[i+1]
  end method
 
  method dat(string k, d) as sys
  sys i=find(k)
  if i=0 then
    if max>=n
      print "Array overflow" : return 0
    end if 
    max+=1
    i=max*2-1
    s[i]=k
  end if
  s[i+1]=d
  return i
  end method
 
end class
 
 
'====
'TEST
'====
 
AssociativeArray A
 
'fill
A.s<={"shoes","LC1",  "ships","LC2",  "sealingwax","LC3",  "cabbages","LC4",  "kings","LC5"}
A.max=5
'access
print A.dat("ships")       'result LC2
A.dat("computers")="LC99"  '
print A.dat("computers")   'result LC99
 