add sets.pop procedure (analogue to python) (#8383)

This commit is contained in:
skilchen
2018-07-21 19:51:14 +02:00
committed by Andreas Rumpf
parent f3926b5af1
commit 8fe8bed9c3
2 changed files with 34 additions and 0 deletions

View File

@@ -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`.
##

22
tests/sets/tsetpop.nim Normal file
View File

@@ -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