RingDotNetfor Ring

Sets

A set holds each value once and finds a value very fast. HashSet also does the operations of set theory — union, intersection, difference — and answers questions such as "is this a subset?". This lesson uses it to remove duplicates and to compare groups.

What you will learn#

The tutorial More data structures showed SortedSet, a set that keeps its values in order. HashSet does not keep an order, and it is faster.

The program#

samples/UsingDotNet/tutorials/ch04_sets.ring
# sets - HashSet, union, intersection, difference, subsets, and how a set removes duplicates and finds common items fast
load "dotnet.ring"

using {
	"System"
}

func main

	cText = "System.String"

	# A set holds each value ONCE and has no order. Adding a value that is already there changes nothing. Looking for a value is
	# very fast, even with a million values, because a set uses a hash table (a list has to look at every item).
	oSetA = makeSet(["ring","dotnet","linq","json","web"])
	oSetB = makeSet(["web","json","tcp","udp","ring","ring"])
	? "1. A has " + oSetA.Count + " items: " + sortedText(oSetA)
	? "   B has " + oSetB.Count + " items (the list had 6, 'ring' twice): " + sortedText(oSetB)

	# 2. The result of Add says whether the value was new
	? nl + "2. Add('tcp') to A: " + oSetA.Add("tcp") + " (new), Add('tcp') again: " + oSetA.Add("tcp") + " (already there)"
	oSetA.Remove("tcp")

	# 3. The four operations of set theory. They CHANGE the set they are called on, so each one works on a copy.
	? nl + "3. A = " + sortedText(oSetA) + "   B = " + sortedText(oSetB)
	oUnion = copySet(oSetA)
	oUnion.UnionWith(oSetB)
	? "   union (in A or B):               " + sortedText(oUnion)
	oBoth = copySet(oSetA)
	oBoth.IntersectWith(oSetB)
	? "   intersection (in A and in B):    " + sortedText(oBoth)
	oOnlyA = copySet(oSetA)
	oOnlyA.ExceptWith(oSetB)
	? "   difference (in A but not in B):  " + sortedText(oOnlyA)
	oEither = copySet(oSetA)
	oEither.SymmetricExceptWith(oSetB)
	? "   in A or B but not in both:       " + sortedText(oEither)

	# 4. Questions about two sets
	oSmall = makeSet(["ring","json"])
	? nl + "4. {ring, json} is a subset of A:  " + oSmall.IsSubsetOf(oSetA)
	? "   A is a superset of {ring, json}: " + oSetA.IsSupersetOf(oSmall)
	? "   A and B have items in common:  " + oSetA.Overlaps(oSetB)
	? "   A and {tcp, udp} have items in common: " + oSetA.Overlaps(makeSet(["tcp","udp"]))
	? "   A equals A with the same items in another order: " + oSetA.SetEquals(makeSet(["web","json","linq","dotnet","ring"]))

	# 5. A set with a comparer: names that differ only in case are the same item (the tutorial "Comparing text")
	oNames = new HashSet([ :typeArguments = [cText], :comparer = new StringComparer().OrdinalIgnoreCase ])
	for cName in ["Ann","ann","BOB","Bob","Cy"]
		oNames.Add(cName)
	next
	? nl + "5. five names, case ignored: " + oNames.Count + " different people"

	# 6. Removing duplicates from a Ring list is one line with a set. The order of a HashSet is not defined: sort when it matters.
	aWithDuplicates = [5,3,5,1,3,8,1,5]
	oIntSet = new HashSet([ :typeArguments = ["System.Int32"] ])
	for nNumber in aWithDuplicates
		oIntSet.Add(nNumber)
	next
	aUnique = sort(oIntSet.toList())
	? nl + "6. " + len(aWithDuplicates) + " numbers, " + len(aUnique) + " different: " + list2text(aUnique)

func makeSet aList

	oSet = new HashSet([ :typeArguments = ["System.String"] ])
	for cItem in aList
		oSet.Add(cItem)
	next
	return oSet

# a copy of a set: the constructor of HashSet takes a collection
func copySet oSet

	return new HashSet([ :typeArguments = ["System.String"], :collection = oSet ])

func sortedText oSet

	return list2text(sort(oSet.toList()))

func list2text aList

	cText = ""
	for item in aList
		cText += "" + item + " "
	next
	return cText
Output
1. A has 5 items: dotnet json linq ring web 
   B has 5 items (the list had 6, 'ring' twice): json ring tcp udp web 

2. Add('tcp') to A: 1 (new), Add('tcp') again: 0 (already there)

3. A = dotnet json linq ring web    B = json ring tcp udp web 
   union (in A or B):               dotnet json linq ring tcp udp web 
   intersection (in A and in B):    json ring web 
   difference (in A but not in B):  dotnet linq 
   in A or B but not in both:       dotnet linq tcp udp 

4. {ring, json} is a subset of A:  1
   A is a superset of {ring, json}: 1
   A and B have items in common:  1
   A and {tcp, udp} have items in common: 0
   A equals A with the same items in another order: 1

5. five names, case ignored: 3 different people

6. 8 numbers, 4 different: 1 3 5 8
Note

This program uses a few generic functions (dnNewGeneric, callMethod) where a class cannot be used. The lesson The generic functions explains them.

How it works#

One copy of each value#

A set holds a value once. The list for set B has six words, ring twice, and the set has five items. Add answers whether the value was new (true) or already there (false); Remove takes a value away. There is no order: the items come out in an order that you must not depend on, so the program sorts them before printing. The set is stored in a hash table: a value is turned into a number that points at the place where it lives, so Contains takes the same short time for ten values and for ten million, while a list has to look at every item. When a program asks "have I seen this before?" many times, a set is the right tool.

StringSet is the ready class for HashSet<string>, and it is used like any object (oSet.Add(...), oSet.Count); toList() copies the items into a Ring list (the tutorial Collections for many threads).

The operations#

Take A = {dotnet, json, linq, ring, web} and B = {json, ring, tcp, udp, web}:

MethodMeaningResult
UnionWith(B)in A or Bdotnet json linq ring tcp udp web
IntersectWith(B)in A and in Bjson ring web
ExceptWith(B)in A but not in Bdotnet linq
SymmetricExceptWith(B)in one of them, not in bothdotnet linq tcp udp

All four change the set they are called on, they do not return a new set. So the program first makes a copy (a HashSet can be made from another collection: copySet) and then changes the copy. If you forget this, A is spoiled for the next step.

Questions#

IsSubsetOf, IsSupersetOf, Overlaps (do they share at least one item?) and SetEquals (the same items, whatever the order) answer yes or no and change nothing. They are what you need for rules such as "the user has all the required permissions" (the set of required permissions is a subset of the user's) or "the two groups have nobody in common" (they do not overlap).

A comparer#

The constructor of a HashSet can take a comparer (the tutorial Comparing text): with StringComparer.OrdinalIgnoreCase, Ann and ann are the same item, so five names make three people.

Removing duplicates#

To remove the duplicates of a Ring list, add its items to a set and read the set back: the 8 numbers in step 6 give 4 different ones. Sort the result if you need an order, because the set has none. This is much faster than looking for each item in a growing list, and it needs only a few lines.

Note

A HashSet<T> needs a good hash and equality for its type. Texts and numbers have them. For your own objects, give the set an equality comparer, or use a text key (such as an id).

What you learned#

Exercises#

  1. Find the words that two text files have in common (the tutorial Files and folders).
  2. Check that a user has all the permissions of a list with IsSupersetOf (the tutorial Identities and claims).
  3. Count the different words of a text (the tutorial Working with text).
  4. Compare Contains in a HashSet and in a Ring list with 100 000 items and a Stopwatch.

Next#

More data structures

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.