tsetutils.nim 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. discard """
  2. matrix: "--mm:refc; --mm:orc"
  3. targets: "c js"
  4. """
  5. import std/setutils
  6. import std/assertions
  7. type
  8. Colors = enum
  9. red, green = 5, blue = 10
  10. Bar = enum
  11. bar0 = -1, bar1, bar2
  12. template main =
  13. block: # toSet
  14. doAssert "abcbb".toSet == {'a', 'b', 'c'}
  15. doAssert toSet([10u8, 12, 13]) == {10u8, 12, 13}
  16. doAssert toSet(0u16..30) == {0u16..30}
  17. type A = distinct char
  18. doAssert [A('x')].toSet == {A('x')}
  19. block: # fullSet
  20. doAssert fullSet(Colors) == {red, green, blue}
  21. doAssert fullSet(char) == {0.chr..255.chr}
  22. doAssert fullSet(Bar) == {bar0, bar1, bar2}
  23. doAssert fullSet(bool) == {true, false}
  24. block: # complement
  25. doAssert {red, blue}.complement == {green}
  26. doAssert (complement {red, green, blue}).card == 0
  27. doAssert (complement {false}) == {true}
  28. doAssert {bar0}.complement == {bar1, bar2}
  29. doAssert {range[0..10](0), 1, 2, 3}.complement == {range[0..10](4), 5, 6, 7, 8, 9, 10}
  30. doAssert {'0'..'9'}.complement == {0.char..255.char} - {'0'..'9'}
  31. block: # `[]=`
  32. type A = enum
  33. a0, a1, a2, a3
  34. var s = {a0, a3}
  35. s[a0] = false
  36. s[a1] = false
  37. doAssert s == {a3}
  38. s[a2] = true
  39. s[a3] = true
  40. doAssert s == {a2, a3}
  41. block: # set symmetric difference (xor), https://github.com/nim-lang/RFCs/issues/554
  42. type T = set[range[0..15]]
  43. let x: T = {1, 4, 5, 8, 9}
  44. let y: T = {0, 2..6, 9}
  45. let res = symmetricDifference(x, y)
  46. doAssert res == {0, 1, 2, 3, 6, 8}
  47. doAssert res == (x + y - x * y)
  48. doAssert res == ((x - y) + (y - x))
  49. var z = x
  50. doAssert z == {1, 4, 5, 8, 9}
  51. doAssert z == x
  52. z.toggle(y)
  53. doAssert z == res
  54. z.toggle(y)
  55. doAssert z == x
  56. z.toggle({1, 5})
  57. doAssert z == {4, 8, 9}
  58. z.toggle({3, 8})
  59. doAssert z == {3, 4, 9}
  60. main()
  61. static: main()