Is it possible to create a dictionary like python by typing only:
var a = {"key_1": "value_1", "key_2": "value_2"}
Instead of?
var a = {"key_1": "value_1", "key_2": "value_2"}.toTable
or something similar to what is used by sequences:
var x = @[1, 2, 3]
var a = %{"key_1": "value_1", "key_2": "value_2"}
It reminds me Perl arrays (@) and hashes (%).
How to make a macro to implement the "%" before "{}"?
proc `%`[T,G,H](a : array[T,(G,H)]) : Table[G,H] =
wow, I had to read that three times before it sank in
The T should probably be renamed N for convention, possibly tagging it with static int as well.
Also it's true that {key: value} syntax creating an array of tuples is not well documented/visible.
I think using @ instead of the % is perfect. Its just like the array syntax.
var a = @[1, 2, 3]
var b = @{"key_1": "value_1", "key_2": "value_2"}
{} is a sugar for array of tuples, so @ already works with it by just making a sequence.
echo @{"key_1": "value_1", "key_2": "value_2"}
results in
@[("key_1", "value_1"), ("key_2", "value_2")]
What prevents it from being used only like this without "%", "@" or "toTable"?
var a = {"key_1": "value_1", "key_2": "value_2"}
It's simple and everyone understands!I did this small test and I don't see any problems or incompatibility. Can someone show me where the use of the "%" can fail? Can someone show me an example where the "%" is used in JSON as in tables "%{}"?
import tables
from strutils import `%`
import json
proc `%`[T,G,H](a : array[T,(G,H)]) : Table[G,H] =
a.toTable()
# Table
var h = %{"key_1": "value_1", "key_2": "value_2"}
echo h
echo h["key_1"]
# JSON
var j = %*{"key_1": "value_1", "key_2": "value_2"}
echo j
echo j["key_1"]
Result:
$ nim c -r test.nim
Hint: operation successful (34378 lines compiled; 8.349 sec total; 46.828MiB peakmem; Debug Build) [SuccessX]
Hint: /home/hdias/Downloads/test [Exec]
{"key_1": "value_1", "key_2": "value_2"}
value_1
{"key_1": "value_1", "key_2": "value_2"}
"value_1"