hi
i want to build up a table/dictionary/hash using strings an keys and hashSet[string] as values. i imagine it working somewhat like python's defaultDict or ruby's default block.
nim -v
Nim Compiler Version 0.14.0 (2016-06-06) [Linux: amd64]
Copyright (c) 2006-2016 by Andreas Rumpf
git hash: b0848101e00080c5b3af3c6ff18b5f1955e69c5c
active boot switches: -d:release
import tables
import sets
var sorted_dict = initTable[string, HashSet[string]]()
sorted_dict.getOrDefault("abc").incl("xyz")
echo sorted_dict["abc"]
i get
test.nim(6, 32) Error: type mismatch: got (HashSet[system.string], string)
but expected one of:
proc incl[T](x: var set[T]; y: T)
template incl[T](s: var set[T]; flags: set[T])
proc incl[A](s: var HashSet[A]; other: OrderedSet[A])
proc incl[A](s: var HashSet[A]; other: HashSet[A])
proc incl[A](s: var HashSet[A]; key: A)
proc incl[A](s: var OrderedSet[A]; key: A)
i am a new nim user and i am unsure what the error complains about. is my implementation completely wrong or is there a difference between "system.string" and "string" ?
any help to move forward with this?
thanks so much
Your problem is that tables.getOrDefault doesn't returns a var reference.
proc getOrDefault[A, B](t: Table[A, B]; key: A): B
You should instead use
proc mgetOrPut[A, B](t: var Table[A, B]; key: A; val: B): var B
#retrieves value at t[key] or puts val if not present, either way returning a value which can be modified.
like this:
# global scope
let EMPTY_HASHSET = initSet[string]()
# and in your code
# if value not found it insert EMPTY_HASHSET (deep copy) and then return a var reference to the value.
sorted_dict.mgetOrPut("abc", EMPTY_HASHSET).incl("xyz")