Skip to content

Commit

Permalink
Adds toSet to create sets from iterables (nim-lang#16276)
Browse files Browse the repository at this point in the history
  • Loading branch information
beef331 authored and mildred committed Jan 11, 2021
1 parent 1e6ec38 commit 1bfeb08
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@
- `strscans.scanf` now supports parsing single characters.
- `strscans.scanTuple` added which uses `strscans.scanf` internally, returning a tuple which can be unpacked for easier usage of `scanf`.

- Added `setutils.toSet` that can take any iterable and convert it to a built-in set,
if the iterable yields a built-in settable type.

- Added `math.isNaN`.

Expand Down
32 changes: 32 additions & 0 deletions lib/std/setutils.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#
#
# The Nim Compiler
# (c) Copyright 2020 Nim Contributors
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#

## This module adds functionality to the built-in `set` type.
## See also std/packedsets, std/sets

import typetraits

#[
type SetElement* = char|byte|bool|int16|uint16|enum|uint8|int8
## The allowed types of a built-in set.
]#

template toSet*(iter: untyped): untyped =
## Return a built-in set from the elements of iterable `iter`
runnableExamples:
assert "helloWorld".toSet == {'W', 'd', 'e', 'h', 'l', 'o', 'r'}
assert toSet([10u16, 20, 30]) == {10u16, 20, 30}
assert [30u8, 100, 10].toSet == {10u8, 30, 100}
assert toSet(@[1321i16, 321, 90]) == {90i16, 321, 1321}
assert toSet([false]) == {false}
assert toSet(0u8..10) == {0u8..10}
var result: set[elementType(iter)]
for x in iter:
incl(result, x)
result
14 changes: 14 additions & 0 deletions tests/stdlib/tsetutils.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
discard """
targets: "c js"
"""
import std/setutils

template main =
doAssert "abcbb".toSet == {'a', 'b', 'c'}
doAssert toSet([10u8, 12, 13]) == {10u8, 12, 13}
doAssert toSet(0u16..30) == {0u16..30}
type A = distinct char
doAssert [A('x')].toSet == {A('x')}

main()
static: main()

0 comments on commit 1bfeb08

Please sign in to comment.