Associative arrays in Nim
One thing that I like very much about BaCon is the simple implementation of associative arrays:
https://www.basic-converter.org/documentation.html#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:
https://scripter.co/notes/nim#critbits
...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": "https://somewhere.com", "InstalledSize": "", "Package": "", "STARTMARKER": "", "Section": "", "Version": ""}
Length: 10
{"Architecture": "x86", "Depends": "", "Description": "", "Filename": "", "Homepage": "https://somewhere.com", "InstalledSize": "", "Package": "", "STARTMARKER": "", "Section": "", "Version": ""}
true
true
false
{"Architecture": "x86", "Depends": "", "Description": "", "Filename": "", "Homepage": "https://somewhere.com", "InstalledSize": "", "Package": "", "STARTMARKER": "", "Version": ""}
{"AnotherKey": "value for new key", "Architecture": "x86", "Depends": "", "Description": "", "Filename": "", "Homepage": "https://somewhere.com", "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":
https://nim-lang.org/docs/critbits.html
If you need an explanation about what associative arrays are:
https://brilliant.org/wiki/associative-arrays/
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:
x86
valueArch=x86
...yes, can read a value from the array as well.
Tags: easy