Skip to content

Commit

Permalink
add sets.pop procedure (analogue to python) (nim-lang#8383)
Browse files Browse the repository at this point in the history
  • Loading branch information
skilchen authored and timotheecour committed Jul 23, 2018
1 parent 57f4a5d commit 8d63926
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
12 changes: 12 additions & 0 deletions lib/pure/collections/sets.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
##
Expand Down
22 changes: 22 additions & 0 deletions tests/sets/tsetpop.nim
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 8d63926

Please sign in to comment.