Add setutils.complement, setutils.fullSet (#17066)
This commit is contained in:
parent
148e5ba2a5
commit
35ded02074
3 changed files with 55 additions and 9 deletions
|
|
@ -14,7 +14,7 @@
|
|||
## * `std/packedsets <packedsets.html>`_
|
||||
## * `std/sets <sets.html>`_
|
||||
|
||||
import std/typetraits
|
||||
import std/[typetraits, macros]
|
||||
|
||||
#[
|
||||
type SetElement* = char|byte|bool|int16|uint16|enum|uint8|int8
|
||||
|
|
@ -35,3 +35,26 @@ template toSet*(iter: untyped): untyped =
|
|||
for x in iter:
|
||||
incl(result, x)
|
||||
result
|
||||
|
||||
macro enmRange(enm: typed): untyped = result = newNimNode(nnkCurly).add(enm.getType[1][1..^1])
|
||||
|
||||
proc fullSet*(T: typedesc): auto {.inline.} =
|
||||
## Returns a full set of all valid elements.
|
||||
runnableExamples:
|
||||
assert {true, false} == fullSet(bool)
|
||||
when T is Ordinal:
|
||||
{T.low..T.high}
|
||||
else: # Hole filled enum
|
||||
enmRange(T)
|
||||
|
||||
proc complement*[T](s: set[T]): set[T] {.inline.} =
|
||||
## Returns the complement of the set.
|
||||
## Can also be thought of as inverting the set.
|
||||
runnableExamples:
|
||||
type Colors = enum
|
||||
red, green = 3, blue
|
||||
assert complement({red, blue}) == {green}
|
||||
assert complement({red, green, blue}).card == 0
|
||||
assert complement({range[0..10](0), 1, 2, 3}) == {range[0..10](4), 5, 6, 7, 8, 9, 10}
|
||||
assert complement({'0'..'9'}) == {0.char..255.char} - {'0'..'9'}
|
||||
fullSet(T) - s
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue