site  contact  subhomenews

Associative arrays in Nim

August 23, 2022 — BarryK

One thing that I like very much about BaCon is the simple implementation of associative arrays:

At first glance, I could not see that capability in Nim, and a search came up with something about using tables -- and the example given was unclear.

Then I discovered this:

...the author hasn't identified himself/herself, but thanks for documenting your process of discovery.

Yes, it turns out that associative arrays is a piece of cake with critbits. Here is my example program:


...I was thinking of rewriting 'debdb2pupdb.bac' in Nim code, hence those array fields created in the above code. Those other modules, "os", and "strutils", are not needed in this code example.

Here is how I compiled it:

# nim c -d:release --opt:size --mm:arc assoctest.nim
# strip assoctest

And the 'assoctest' binary is 39KB. Without that "--mm:arc" it will use the default garbage collection, and size is 47KB. Good. Running it:

# ./assoctest 
{"Architecture": "amd64", "Depends": "", "Description": "", "Filename": "", "Homepage": "", "InstalledSize": "", "Package": "", "STARTMARKER": "", "Section": "", "Version": ""}
Length: 10

{"Architecture": "x86", "Depends": "", "Description": "", "Filename": "", "Homepage": "", "InstalledSize": "", "Package": "", "STARTMARKER": "", "Section": "", "Version": ""}

{"Architecture": "x86", "Depends": "", "Description": "", "Filename": "", "Homepage": "", "InstalledSize": "", "Package": "", "STARTMARKER": "", "Version": ""}
{"AnotherKey": "value for new key", "Architecture": "x86", "Depends": "", "Description": "", "Filename": "", "Homepage": "", "InstalledSize": "", "Package": "", "STARTMARKER": "", "Version": "", "YetAnotherKey": "value2 for another key"}
Length: 11

The source code is really self-explanatory. Very simple, I like it.

Here is the reference on "critbits":

If you need an explanation about what associative arrays are:

Yes, you treat them just like normal arrays, except the key is not an index-value. I added this extra code to the example:


Running it:


...yes, can read a value from the array as well.  

Tags: easy