Hi all,
I have a problem finding a solution for a problem (or perhaps i am looking the wrong direction). I want to check if a key is already set and if that is the case, overwrite it with the new value. Off course there is the possibility to walk through the whole sequence to see if a key exists, but is there a smarter way?
I only have this code :
type
DataBuffer* = tuple
key : string
mytype : string
value : string
var mydata = newSeq[DataBuffer]()
mydata.add(("a","int","4"))
mydata.add(("a","int","5"))
echo mydata # if expect only the last add to be visible ([a, int, 5])
implement proc == and contains for you specialized type
import sequtils
type
DataBuffer* = tuple
key : string
mytype : string
value : string
proc `==`(a, b: DataBuffer): bool =
a.key == b.key
proc contains[T: DataBuffer](d: T, dbuf: seq[T]): bool =
for data in dbuf:
if d == data:
return true
false
# change proc to be different to work with generic add
proc dataAdd[T: DataBuffer](data: var seq[T], newdata: T): bool {.discardable.} =
if newdata in data:
data[data.find(newdata)] = newdata
false
else:
data.add newdata
true
var mydata = newSeq[DataBuffer]()
mydata.dataAdd(("a","int","4"))
mydata.dataAdd(("a","int","5"))
echo mydata # if expect only the last add to be visible ([a, int, 5])
With boolean return, you can know whether it replaced old value or add new to collections. You can just change the dataAdd to return DataBuffer so it will return old value that's be replaced or return a newly added value.
@mashigan & @miran Ty guys, you both point me to tables and i also thought that tables would solve my problem. I thought that tableref would reference the content like record number. But it reference the whole table. The point is that i want to prevent to walk through the whole table to see if a value exists. But i think that there is no other option.
But now i am thinking/talking about it, i suddenly have a idea what would solve this. Because i know what the key's are before compilation.
Thanks guys.