Pretty much nothing from the standard library provides any examples. I don't know how to get from the description of types in the tables module to a working declaration.
import tables var dict_table : TTable[A,B]
does not work
Do I first declare a type and then declare my variable with that type?
import tables
does not work.
Other times it seems things need to be declared as object, but that is really a struct--a different data structure.
I am sure this is easy, but there is no place to start. I look at every example in the download and there are no examples of a table being declared. I have looked through dozens of the samples at Rosetta Code and, despite lots of useful examples, haven't found a one that contains a table declaration.
Araq knows how to do it implicitly, but there are so many implied idioms that are very opaque without some kind of starter and examples FOR EVERYTHING.
You need to use initTable
http://nimrod-lang.org/tables.html
i.e.
var values = initTablekeytype, valuetype
This might also help:
Thanks.
I did find nimrod-by-example and looked at all of it. No tables there.
In Tutorial 2 there is an example of using a table. Picked up initTable() from that example.
I stand on my point that the module documentation is WAY too sketchy. The brief descriptions are not suggestive of how to use the module's methods in working code.
However, with the one example and just trying things, made progress. This code works:
import tables
var
menucmds: array[0..6, string]
minidict: TTable[string, string]
menucmds = ["toc", "keys", "all", "values", "q", "quit", "."]
# access the file
echo "Enter name of file containing your mini dictionary: "
var fname = readLine(stdin)
var fhandle = open(fname, fmRead)
for ln in fhandle.lines:
echo ln
minidict = initTable[string, string]()
minidict["this"] = "a word used as an article to identify a specific object"
for k,v in minidict.pairs:
echo k
echo v
There is just not a single thing wrong with the way this works. It's just that the lack of doc renders nim somewhere between opaque and impenetrable. For instance, how would I guess that using the pairs proc as a method doesn't require (), coming from Python. Again, the way nim does it is absolutely fine--it's quite nice in fact. But, it is not discoverable from provided doc. I realize doc is hard to write. Each module reference could/should include an (unrealistic) example that shows each method's signature in a valid use.
No, I can't volunteer. Given the current state of docs, someone who already knows the language needs to do this. It can be downright terse. It can say do x just like y, above. One good pass and then volunteers CAN provide more explanatory text and/or richer or more realistic examples.
Been working through docs slowly.
Omitting () from method call with single argument (self) is in the manual.
Sorry. It's still a bit hard...
The easiest way to initialize a table with a literal is as follows:
import tables
var t = {"foo": 1, "bar":2}.toTable
echo t
The notation {key:value, ...} is syntactic sugar for [[key, value], ...]. The toTable call then converts that array of pairs into a hash table (see this link for the documentation of the toTable procedure).
Thanks for the hint. I would never have figured out how to call this proc from the way it's documented. your example is short and completely clear.
if I were using the long way would the tuple of pairs come after toTable enclosed by square braces or parens?
You need both then:
toTable({"foo": 1, "bar":2})
Thanks. I was confused by Jehan's post of "...syntactic sugar for [[key, value], ...]"
@Araq: building the module doc by using your tool to extract docstrings was certainly fast, much needed with few folks on the project, but the proc docstring from source doesn't really show how the proc needs to be called or how a variable or type needs to be declared in my nim code. Probably, most of the vars/types and procs (or methods depending on how used) in a given module work in a very similar way so they don't ALL need an example. But for noobs like me, a single example (human authored and very minimal) showing a var declaration, type declaration, and proc/method invocation at the top of that module's doc would then open doors (for me, at least) to how to write code using that module.
lewisl: Thanks. I was confused by Jehan's post of "...syntactic sugar for [[key, value], ...]"
To clarify: When you type:
{"foo":1, "bar": 2}
this is exactly the same as typing:
[("foo", 1), ("bar", 2)]
You can see this by running:
echo repr({"foo":1, "bar":2})
I.e., it's a different notation for arrays of tuples with two items each (the inner brackets were a typo, sorry, it should have been [(key, value), ...]).
When a function has only a single argument, you do not always need parentheses. E.g., the following works fine:
import math
let x = sin PI/2
However, if the argument begins with a brace or bracket, then you will need to surround it with parentheses. This is because f[x] and f{x} can also be read as indexing operations. In particular, you can define operators {} and {}=, e.g.:
proc `{}`(x: int, n: int): bool =
bool((x shr n) and 1)
proc `{}=`(x: var int, n: int, val: bool) =
x = x or (int(val) shl n)
var a = 5
echo a{0}, " ", a{1}, " ", a{2}
a{1} = true
echo a
This is why toTable {"foo":1, "bar":2} confuses the compiler, which tries to read the {...} part following an identifier as an indexing operator rather than a literal.
Not sure if the forum will bump this post up, but I just started reading the docs, couldnt find how to do this, and this forum post was the first thing I found searching with a number of terms in Google.
It looked like there were no hash tables in Nim on reading the tutorial (http://nim-lang.org/tut1.html) to me, before I saw this thread.
@ghowland Go to Nim homepage, click on "docs" at the top bar (seemingly logical choice if you want to find something out), then click on the first link on the page called "Libraries" (again, a fairly logical choice given that most languages have Hashtables in a library), then on that page filled with lots of boring stuff to read... :) oh wait, third link in the TOC to the left says "Collections" - that sounds right, or just press ctrl-f and type in "hash table".
Now... one or even two tutorials (we have two) can't be expected to cover all things about Nim. When you have read both tutorials and the language manual, and at least briefly skimmed the list of libraries available in the standard libs - if major things are still not found, then I agree.
Having said that, I am all for more documentation and try to do my part as a newbie (I am too) by writing articles. We should link them more properly from nim-lang.org, but you can find mine here:
http://goran.krampe.se/category/nim
I am also in the process of setting up a planet Nim which will make it easier to track us who blog on Nim, but its not up just yet, within a week though.
In fact I had to search myself some time ago and the answer was not obvious in the doc
the best help I had was with Rosetta 'http://rosetta.alhur.es/compare/Python/Nimrod/#'
echo "\n\n######## DEMO HASH TABLE"
import tables
var
hash = initTable[string, int]() # empty hash table
hash2 = {"key1": 1, "key2": 2}.toTable # hash table with two keys
hash3 = [("key1", 1), ("key2", 2)].toTable # hash table from tuple array
hash4 = @[("key1", 1), ("key2", 2)].toTable # hash table from tuple seq
value = hash2["key1"]
hash["spam"] = 1
hash["eggs"] = 2
hash.add("foo", 3)
echo "hash has ", hash.len, " elements"
import tables
var t1 = {"key1":6, "key2":12}.toTable
var t2 = toTable({"key1":6, "key1":12})
echo t1,t2
To be fair, the docs seem geared towards language grammar/specification, which is probably for the best, if there is only one version of the docs.
Additionally I prefer a programmers cheat sheet, with concise snippets, concise comments only if absolutely helpful, and no side commentary.
Python and most of MSDN are similar, often being too verbose regarding grammar, and too skimpy with examples, for me, as a programmer. Which may be why I have my own collection of notes for C++,VB,C,C#,Python,Javascript,SQL and now, Nim! :)
Thanks for the amazing work!