Any tips on how to add to a seq that is inside an ordered table? I am not sure how to accomplish this as the code below does not work. Any tips or suggestions is greatly appreciated. Thank you kindly.
var rates = initOrderedTable[string, seq[string]]()
for r in measuredResults:
if r.rate notin rates:
rates[r.rate].add(r.frequency)
else:
if r.frequency notin rates[r.rate]:
rates[r.rate].add(r.frequency)
Can you show more code?, I do not understand the tiny fragment.
Have you tried using table[key] = value ?
Mayte this in the forse Of?
rates[r.rate] = @[r.frequency]
Perfect! This did the trick.
Thank you for the help.
This might be slightly faster or at least show some other Nim options:
import tables
proc addUnique[T](xs: var seq[T], x: T) =
if x notin xs: xs.add x
var rates = initOrderedTable[string, seq[string]]()
for r in [(rate: "1", freq: "2"), (rate: "3", freq: "4"),
(rate: "1", freq: "2"), (rate: "3", freq: "5")]:
rates.mgetOrPut(r.rate, @[]).addUnique r.freq
There is also mgetOrPut, which you can use like this:
for r in measuredResults:
rates.mgetOrPut(r.rate, @[]).add(r.frequency)
- the original notin applied to unordered seq replicated in my example code
- use a sets.HashSet if order of the frequencies does not matter
- use algorithm.upperBound to test for existence/keep things ordered via binary search
- stdlib critbits or a binary search tree (BST)
- use a B-tree such as in my adix or @miran's sorta.
That doesn't take care of not having duplicates.
Ah, right. I didn't catch that detail in the original post. Then, I would use HashSet instead of a seq (if order is not important, of course).
Why this code doesn't work, updating the list var list = table[key] doesn't update the table.
Didn't it supposed to update the table, as var shouldn't copy the list?
import tables
var table: Table[string, seq[string]]
table["a"] = @[]
table["a"].add "1" # Updates table
var list = table["a"]
list.add "2" # Doesn't update the table
echo table
seqs have value semantics, why would it not perform a copy?
you can override that with .byaddr, however:
import std/[tables,decls]
var table: Table[string, seq[string]]
table["a"] = @[]
table["a"].add "1" # Updates table
var list{.byaddr.} = table["a"]
list.add "2" # Updates the table
echo table # ==> {"a": @["1","2"]}
I guess my confusion goes from the fact that var behaves differently depending if it's a variable declaration, or attribute declaration.
In example below in one case it will create copy, in another use reference
var list = @[1]
# var as a copy
var copy = list
copy.add 2
assert list == @[1] # original not affected
# var as reference
proc add2(list: var seq[int]) = list.add 2
add2 list
assert list == @[1, 2] # original affected