A number of times I've wanted to iterate through a sequence and delete various items in it.
However, that causes errors. I'm curious if there is an idiomatic Nim way to do it? I'm sorta hoping there's a nice tool in system.nim?
what I usually do is something like this:
var i = 0
while i < myseq.len:
if deleteCond:
myseq.del i
else:
i += 1
it also works with both delete and del, but is admitedly not that pretty.
It's probably best to iterate in reverse and use del, this way you don't need to double check the condition on the same index after the swap.
## Retains elements of a sequence specified by the predicate.
## Does not preserve order!
proc retain[T](s: var seq[T]; pred: proc(x: T): bool {.closure.}) =
for i in countDown(s.len-1, 0):
if not pred(s[i]): s.del(i)
var a = @[10, 11, 12, 13, 14]
a.retain(proc(x: int): bool = (x mod 2 == 0))
echo a