Maps in Pascal

Maps are Pascal’s built-in associative data type (sometimes called hashes or dicts in other languages).

program MapsExample;

uses
  SysUtils, Generics.Collections, FGL;

var
  m: specialize TFPGMap<string, integer>;
  n, n2: TDictionary<string, integer>;
  v1, v3: integer;
  prs: boolean;
begin
  // To create an empty map, use the generic class TFPGMap.
  m := specialize TFPGMap<string, integer>.Create;

  // Set key/value pairs.
  m.Add('k1', 7);
  m.Add('k2', 13);

  // Printing a map will show all of its key/value pairs.
  WriteLn('map: ');
  for var i := 0 to m.Count - 1 do
    WriteLn(m.Keys[i], ': ', m.Data[i]);

  // Get a value for a key.
  v1 := m['k1'];
  WriteLn('v1: ', v1);

  // If the key doesn’t exist, the default value is returned.
  v3 := m['k3'];
  WriteLn('v3: ', v3);

  // TFPGMap doesn't directly support length, so we use the Count property.
  WriteLn('len: ', m.Count);

  // Remove key/value pairs.
  m.Delete(m.IndexOf('k2'));
  WriteLn('map: ');
  for var i := 0 to m.Count - 1 do
    WriteLn(m.Keys[i], ': ', m.Data[i]);

  // Clear all key/value pairs.
  m.Clear;
  WriteLn('map: ');
  for var i := 0 to m.Count - 1 do
    WriteLn(m.Keys[i], ': ', m.Data[i]);

  // The optional second return value when getting a value from a map indicates if the key was present.
  prs := m.IndexOf('k2') <> -1;
  WriteLn('prs: ', prs);

  // Declare and initialize a new map in the same line with this syntax.
  n := TDictionary<string, integer>.Create;
  n.Add('foo', 1);
  n.Add('bar', 2);
  WriteLn('map: ');
  for var pair in n do
    WriteLn(pair.Key, ': ', pair.Value);

  // The Generics.Collections unit contains a number of useful utility functions for maps.
  n2 := TDictionary<string, integer>.Create;
  n2.Add('foo', 1);
  n2.Add('bar', 2);
  if n.Equals(n2) then
    WriteLn('n == n2');
end.

Note that maps appear in the form [k:v k:v] when iterated through and printed.

$ fpc MapsExample.pas
$ ./MapsExample
map: 
k1: 7
k2: 13
v1: 7
v3: 0
len: 2
map: 
k1: 7
map: 
prs: false
map: 
foo: 1
bar: 2
n == n2

Next example: Functions.