From 070a1d7e169bf33710e857de27c771ebdf10f3ab Mon Sep 17 00:00:00 2001 From: skilchen Date: Sat, 21 Jul 2018 19:51:14 +0200 Subject: [PATCH] add sets.pop procedure (analogue to python) (#8383) --- lib/pure/collections/sets.nim | 12 ++++++++++++ tests/sets/tsetpop.nim | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 tests/sets/tsetpop.nim diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim index 59c90bc2ba85e..fdc3b4b03aa8f 100644 --- a/lib/pure/collections/sets.nim +++ b/lib/pure/collections/sets.nim @@ -347,6 +347,18 @@ proc excl*[A](s: var HashSet[A], other: HashSet[A]) = assert other.isValid, "The set `other` needs to be initialized." for item in other: discard exclImpl(s, item) +proc pop*[A](s: var HashSet[A]): A = + ## Remove and return an arbitrary element from the set `s`. + ## + ## Raises KeyError if the set `s` is empty. + ## + for h in 0..high(s.data): + if isFilled(s.data[h].hcode): + result = s.data[h].key + excl(s, result) + return result + raise newException(KeyError, "set is empty") + proc containsOrIncl*[A](s: var HashSet[A], key: A): bool = ## Includes `key` in the set `s` and tells if `key` was added to `s`. ## diff --git a/tests/sets/tsetpop.nim b/tests/sets/tsetpop.nim new file mode 100644 index 0000000000000..c37bda57d9fbf --- /dev/null +++ b/tests/sets/tsetpop.nim @@ -0,0 +1,22 @@ +discard """ + targets: "c c++ js" + output: '''1000 +0 +set is empty +''' +""" + +import sets + +var a = initSet[int]() +for i in 1..1000: + a.incl(i) +echo len(a) +for i in 1..1000: + discard a.pop() +echo len(a) + +try: + echo a.pop() +except KeyError as e: + echo e.msg \ No newline at end of file