diff --git a/compiler/importer.nim b/compiler/importer.nim index f5eb5329d9..dcdd0bb49e 100644 --- a/compiler/importer.nim +++ b/compiler/importer.nim @@ -14,6 +14,7 @@ import semdata, modulepaths, sigmatch, lineinfos, sets, modulegraphs, wordrecg, tables from strutils import `%` +from sequtils import addUnique when defined(nimPreviewSlimSystem): import std/assertions @@ -228,11 +229,6 @@ proc importForwarded(c: PContext, n: PNode, exceptSet: IntSet; fromMod: PSym; im else: for i in 0..n.safeLen-1: importForwarded(c, n[i], exceptSet, fromMod, importSet) - -proc addUnique[T](x: var seq[T], y: sink T) {.noSideEffect.} = - for i in 0..high(x): - if x[i] == y: return - x.add y proc importModuleAs(c: PContext; n: PNode, realModule: PSym, importHidden: bool): PSym = result = realModule diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index e2adba910e..eb9ff32c69 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -140,6 +140,34 @@ func concat*[T](seqs: varargs[seq[T]]): seq[T] = result[i] = itm inc(i) +func addUnique*[T](s: var seq[T], x: sink T) = + ## Adds `x` to the container `s` if it is not already present. + ## Uses `==` to check if the item is already present. + runnableExamples: + var a = @[1, 2, 3] + a.addUnique(4) + a.addUnique(4) + assert a == @[1, 2, 3, 4] + + for i in 0..high(s): + if s[i] == x: return + when declared(ensureMove): + s.add ensureMove(x) + else: + s.add x + +func addUnique*[T](s: var seq[T], xs: sink seq[T]) = + ## Adds any items from `xs` to the container `s` that are not already present. + ## Uses `==` to check if the item is already present. + runnableExamples: + var a = @[1, 2, 3] + a.addUnique(@[3, 4]) + a.addUnique(@[4, 5]) + assert a == @[1, 2, 3, 4, 5] + + for i in 0..high(xs): + addUnique(s, move(xs[i])) + func count*[T](s: openArray[T], x: T): int = ## Returns the number of occurrences of the item `x` in the container `s`. ##