Sets
Posted: Sat Mar 08, 2008 10:07 pm
A set is collection of items without regard to order and without duplication. In logic and mathematics you can talk about the set of all even numbers, or the set of all mammals. You can then explore concepts like the intersection of sets, the union, etc.
In software development, a set is another collection like a list or dictionary. Testing for set membership is very fast because sets use the same quick hash code technique that is used for dictionary keys. They also keep members unique with no duplication. Those are reasons to use them in place of lists. Unlike dictionaries, they don't map keys to values. When you're not conceptually mapping keys to values, that would be a reason to use them in place of dictionaries.
The name of the Cobra class is Set<of T> and is immediately available just like List<of T>. There is also ISet<of T>. Like lists and dictionaries, you can have Set literals. That's enough prose, let's have some code:
You can read the implementation of Set<of> and ISet<of> in CobraLang.cobra under Source.
This is in development, not in the last release (0.7.4).
In software development, a set is another collection like a list or dictionary. Testing for set membership is very fast because sets use the same quick hash code technique that is used for dictionary keys. They also keep members unique with no duplication. Those are reasons to use them in place of lists. Unlike dictionaries, they don't map keys to values. When you're not conceptually mapping keys to values, that would be a reason to use them in place of dictionaries.
The name of the Cobra class is Set<of T> and is immediately available just like List<of T>. There is also ISet<of T>. Like lists and dictionaries, you can have Set literals. That's enough prose, let's have some code:
s = {1, 2, 3} # inferred as Set<of int>
assert 1 in s
assert 4 not in s
t = {2, 3, 4}
assert s.intersection(t) == {3, 2} # order doesn't matter
s2 = {,} # empty set. inferred as Set<of dynamic>
assert s2.count == 0
d1 = {:} # empty dictionary. inferred as Dictionary<of dynamic, dynamic>
d2 = {} # warning that dictionary is assumed, but please use {:} or {,}
s3 = Set<of String>() # explicit typed creation
s3.add('aoeu')
s3.add('asdf')
You can read the implementation of Set<of> and ISet<of> in CobraLang.cobra under Source.
This is in development, not in the last release (0.7.4).