|
Oktatás * Programozás 1 * Szkriptnyelvek Teaching • Programming 1 (BI) Félévek Linkek * kalendárium |
Nim2 /
HashSet and OrderedSetSee also std/sets "Hash sets are different from the built-in set type. Sets allow you to store any value that can be hashed and they don't contain duplicate entries." HashSet is similar to Python's set data structure. First, I present HashSet, and then OrderedSet. import std/sets var a: HashSet[int] # empty set echo a # {} echo a.len # 0 a.incl(2) a.incl(2) a.incl(3) a.incl(3) a.incl(5) echo a # {5, 3, 2} ; unordered var b = initHashSet[int]() # alternative way to create an empty set # var c = newHashSet[int]() # Error: no such function echo b # {} Value typeA set is also value type. That is, when you use the import std/sets # toHashSet var a = [2, 3, 5].toHashSet # .toSet is deprecated echo a.typeof # HashSet[system.int] var b = a # copy, a set has value type b.incl(9) echo a # {3, 2, 5} echo b # {3, 9, 2, 5} Note that Set operationsLet's see the basic operations. What can we do with a set? import std/algorithm import std/sequtils # toSeq(iter), map, filter import std/sets # toHashSet var basket: seq[string] = @["apple", "ananas", "banana", "apple", "orange", "banana"] fruits: HashSet[string] = basket.toHashSet() back: seq[string] = fruits.toSeq echo basket # @["apple", "ananas", "banana", "apple", "orange", "banana"] echo fruits # {"ananas", "banana", "apple", "orange"} echo back # @["ananas", "banana", "apple", "orange"] # echo sorted(fruits) # Error: sorted needs an openArray echo sorted(fruits.toSeq) # @["ananas", "apple", "banana", "orange"] echo "kiwi" in fruits # false echo "apple" in fruits # true Union, intersection, difference: import std/sets # toHashSet var a = ["apple", "banana", "lemon"].toHashSet() b: HashSet[string] # empty set echo a # {"apple", "lemon", "banana"} echo b # {} b.incl("banana") b.incl("orange") echo b # {"banana", "orange"} echo a.union(b) # {"apple", "lemon", "banana", "orange"} ; a new set object is returned echo a # {"apple", "lemon", "banana"} ; `a` didn't change echo a.intersection(b) # {"banana"} echo a.difference(b) # {"apple", "lemon"} echo a # {"apple", "lemon", "banana"} a.excl("lemon") echo a # {"apple", "banana"} OrderedSetIt's very similar to a normal HashSet with the difference that it remembers the insertion order. Otherwise, it's like a HashSet. import std/sets var li = @["apple", "ananas", "banana", "apple", "orange", "banana"] v1 = li.toHashSet() v2 = li.toOrderedSet() echo v1 # {"ananas", "banana", "apple", "orange"} ; order is mixed up echo v2 # {"apple", "ananas", "banana", "orange"} ; the order is kept There is a type union that can represent both sets: SomeSet[A] = HashSet[A] | OrderedSet[A] |
![]() Blogjaim, hobbi projektjeim * The Ubuntu Incident [ edit ] |